我试图学习如何制作角度服务,所以我'我做了一个,但它只在页面加载时起作用,它给出输入值而不是函数结果。
HTML:
<input type="text" ng-model="hexVal">
<p>Hex service: {{hex(hexVal)}}</p>
JS:
服务本身:
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
};
});
服务的使用:
$scope.hexVal = 255;
$scope.hex = function(arg){
return hexafy.myFunc(arg);
};
答案 0 :(得分:1)
输入文本需要解析为数字:
app.service('hexafy', function() {
this.myFunc = function (x) {
return parseInt(x).toString(16);
};
});
angular.module("app",[])
.service('hexafy', function() {
this.myFunc = function (x) {
return parseInt(x).toString(16);
};
})
.controller('ctrl', function($scope,hexafy) {
$scope.hexVal = 255;
$scope.hex = function(arg){
return hexafy.myFunc(arg);
};
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
<input type="text" ng-model="hexVal">
<p>Hex service: {{hex(hexVal)}}</p>
</body>