通过输入使 AngularJS 服务动态化

Making AngularJS service dynamic with input

我是 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.

提前致谢

试试下面给出的服务代码:

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>

享受解决方案。 :)

一种方法是使用 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