通过输入使AngularJS服务动态化

时间:2018-04-30 12:08:59

标签: angularjs angularjs-service

我是AngularJS开发的新手。我正在尝试构建一个动态服务,它使用输入元素更新输出。但是,我每次都会收到错误。

在声明服务功能时我做错了什么。 这是我的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 ng-init="m5=0" ng-model="m5"></input>
    <p>The hexadecimal value of {{m5}} is:</p>
    <h1>{{hex}}</h1>
</div>

我的angularJS应用程序如下:

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

{{hex}}的输出不是动态的。它显示静态值NaN

提前致谢

2 个答案:

答案 0 :(得分:0)

尝试以下给定的服务代码:

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

希望这会为你工作。

但我更喜欢使用过滤器选项。您可以尝试过滤,如: 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>

享受解决方案。 :)

答案 1 :(得分:0)

一种方法是使用ng-change directive

<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"
           ng-change="hex=toHex(m5)" />  ̶<̶/̶i̶n̶p̶u̶t̶>̶
    <p>The hexadecimal value of {{m5}} is:</p>
    <h1>{{hex}}</h1>
</div>

JS

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

每次更改输入值时,$scope.hex都会更新。

有关详细信息,请参阅AngularJS ng-change Directive API Reference