Tejas
Tejas

Reputation: 3

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>

Upvotes: 0

Views: 274

Answers (2)

Praveen M P
Praveen M P

Reputation: 11614

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);
    }

Upvotes: 0

Mistalis
Mistalis

Reputation: 18289

Why it does not work?

In your input, you try to call a function:

<input type="number" ng-model="in" ng-change="hex(in)"> 

But $scope.hex is not a function in your controller:

$scope.hex = hexafy.myFunc($scope.in);

How to fix it?

Change it to:

$scope.hex = function() {
    $scope.result = hexafy.myFunc($scope.in);
}

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 = function() {
        $scope.result = hexafy.myFunc($scope.in);
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
    <input type="number" ng-model="in" ng-change="hex()"> 
    {{in}} <br>{{result}}
</div>

Upvotes: 1

Related Questions