我有一个输入字段,我希望用户输入一个数字,所以我创建了一个输入字段,类型为" number"。
当我在1.2中使用它时,我没有错误
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js"></script>
<script>
var app = angular.module('app', []);
app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.person = [
{"name": "Alex","pts": "10"}
];
}]);
</script>
<div ng-app="app">
<div ng-controller="MainCtrl">
{{person | json }}<br>
name: <span ng-bind="person[0].name"></span></br>
<!-- pts: <input ng-model="person[0].pts"> -->
pts: <input type="number" ng-model="person[0].pts"><br?
</div>
</div>
http://codepen.io/anon/pen/dPKgVL
然而,当我在1.3中使用它时,我得到错误:[ngModel:numfmt]但是当我更新数字时,它似乎仍然被绑定到范围。
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('app', []);
app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.person = [
{"name": "Alex","pts": "10"}
];
}]);
</script>
<div ng-app="app">
<div ng-controller="MainCtrl">
{{person | json }}<br>
name: <span ng-bind="person[0].name">
name: <span ng-bind="person[0].name"></span></br>
<!-- pts: <input ng-model="person[0].pts"> -->
pts: <input type="number" ng-model="person[0].pts">
</div>
</div>
http://codepen.io/anon/pen/YPvJro
我在这里做错了什么或者这没什么好担心的?当我尝试调试其他问题时,我宁愿不在控制台中出现错误
答案 0 :(得分:19)
添加此项以解决问题:
myApp.directive('input', [function() {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
if (
'undefined' !== typeof attrs.type
&& 'number' === attrs.type
&& ngModel
) {
ngModel.$formatters.push(function(modelValue) {
return Number(modelValue);
});
ngModel.$parsers.push(function(viewValue) {
return Number(viewValue);
});
}
}
}
}]);
答案 1 :(得分:11)
将pts
属性定义为number
而不是string
:
var app = angular.module('app', []);
app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.person = [
{"name": "Alex","pts": 10}
];
}]);
答案 2 :(得分:8)
该指令将解析任何类型为&#39; number&#39;的输入的字符串值。然后你就不会有任何错误:
module.directive('input', function(){
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModel){
if(attrs.type == 'number'){
ngModel.$formatters.push(function(value){
return parseFloat(value);
});
}
}
};
});
答案 3 :(得分:2)
删除&#34; 10&#34;周围的引号。 Angular期待一个数字,你给它一个字符串。
答案 4 :(得分:2)
Easy解决方案错误“numfmt的AngularJS文档”解析Int或Float中的类型; - )
<input type="number" ng-model="inputNumDemo" />
....
app.controller('Demo',[ '$scope', function($scope){
// Input numeric convert String "10" to Int 10 or Float
$scope.f.inputNumDemo = parseInt(d.data.inputDemo );
}]);
....
答案 5 :(得分:0)
您好只需在app.js
中添加此代码即可angular.module('numfmt-error-module', [])
.run(function($rootScope) {
$rootScope.typeOf = function(value) {
return typeof value;
};
})
.directive('stringToNumber', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(value) {
return '' + value;
});
ngModel.$formatters.push(function(value) {
return parseFloat(value);
});
}
};
});