如何将数据从输入传递到自定义服务?
How to pass data from input to a custom service?
我是 AngularJS 的新手,我遇到了一个问题:如何显示输入框中输入的数字的十六进制等效值?
我正在使用ng-change
查看输入是否被修改,输出也应该根据输入发生变化。
这是代码:
<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>
为什么不起作用?
在您的输入中,您尝试调用一个函数:
<input type="number" ng-model="in" ng-change="hex(in)">
但 $scope.hex
不是 控制器中的函数:
$scope.hex = hexafy.myFunc($scope.in);
如何解决?
改为:
$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>
已创建 Plunker。问题是您正在使用函数名称作为赋值。
<input type="number" ng-model="in" ng-change="convertToHex(in)">
$scope.convertToHex= function(value) {
$scope.hex = hexafy.myFunc(value);
}
我是 AngularJS 的新手,我遇到了一个问题:如何显示输入框中输入的数字的十六进制等效值?
我正在使用ng-change
查看输入是否被修改,输出也应该根据输入发生变化。
这是代码:
<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>
为什么不起作用?
在您的输入中,您尝试调用一个函数:
<input type="number" ng-model="in" ng-change="hex(in)">
但 $scope.hex
不是 控制器中的函数:
$scope.hex = hexafy.myFunc($scope.in);
如何解决?
改为:
$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>
已创建 Plunker。问题是您正在使用函数名称作为赋值。
<input type="number" ng-model="in" ng-change="convertToHex(in)">
$scope.convertToHex= function(value) {
$scope.hex = hexafy.myFunc(value);
}