Search code examples
javascriptangularjsangularjs-service

How to pass data from input to a custom service?


I am new to AngularJS and I have a problem: how to display the hex equivalent of the number inserted into the input box?

I am using ng-change to see if the input is modified and the output should also change according to the input.

This is the code:

<div ng-app="myApp" ng-controller="myCtrl">
  <input type="number" ng-model="in" ng-change="hex(in)"> 
  {{in}} <br>{{hex}}
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<script>
  var app = angular.module('myApp', []);

  app.service('hexafy', function() {
    this.myFunc = function (x) {
      return x.toString(16);
    }
  });
    
  app.controller('myCtrl', function($scope, hexafy) {
    $scope.in= 11;
    $scope.hex = hexafy.myFunc($scope.in);
  });
</script>


Solution

  • Created Plunker. Problem is that you are using function name as assignment.

     <input type="number" ng-model="in" ng-change="convertToHex(in)"> 
     $scope.convertToHex= function(value) {
           $scope.hex = hexafy.myFunc(value);
        }