angularjsangularjs-service

Making AngularJS service dynamic with input


I am new to AngularJS development. I am trying to build a dynamic service, which updates the output with input elements. But, I am getting error every time.

What am I doing wrong in declaring the service functions. Here is my html code

<div ng-app="myApp" ng-controller="myCtrl">
    <p>A custom service with a method that converts a given number into a hexadecimal number.</p>
    <label>input a number</label>
    <input ng-init="m5=0" ng-model="m5"></input>
    <p>The hexadecimal value of {{m5}} is:</p>
    <h1>{{hex}}</h1>
</div>

my angularJS app is as follows:

var app = angular.module('myApp', []);
app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});
app.controller('myCtrl', function($scope, hexafy) {
    $scope.hex = hexafy.myFunc(parseInt($scope.m5));
});

But my output of {{hex}} is not dynamic. It shows static value NaN.

Thanks in advance


Solution

  • Try below-given service code:

    app.service('hexafy', function() {
        this.myFunc = function (x) {
            return Number(x).toString(16);
        }
    });
    app.controller('myCtrl', function($scope, hexafy) {
        $scope.hex = hexafy.myFunc($scope.m5);
    });
    

    Hope this will work fork for you.

    But I prefer to use filter option for this. You can try filter like:
    AngulrJS

    var app = angular.module('myApp', []);
    
    //Filter to conver input number into hexadecimal number 
    app.filter('hexafy', function () {
      return function(x) {
        return Number(x).toString(16);
      };
    });
    app.controller('myCtrl', ['$scope', 'hexafyFilter', function($scope, hexafyFilter) {
        $scope.m5 = 0;
    }]);
    

    HTML

    <div ng-app="myApp" ng-controller="myCtrl">
        <p>A custom service with a method that converts a given number into a hexadecimal number.</p>
        <label>input a number</label>
        <input type="number" ng-model="m5"></input>
        <p>The hexadecimal value of {{m5}} is:</p>
        <h1>{{ m5 | hexafy }}</h1>
    </div>
    

    Enjoy solution. :)