Reputation: 1340
How do we apply number filter on input field? I works fine on displaying on non-input field. However when I set the filter on input field I get an error.
<input type="number" name="input" ng-model="value2 | number:2"
min="0" max="99" size="20">
Error: [ngModel:numfmt] http://errors.angularjs.org/1.3.8/ngModel/numfmt?p0=98.77 at Error (native) at http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:6:416
Here is a plunk for testing. number format
Upvotes: 2
Views: 2903
Reputation: 11
This error:
Error: [ngModel:numfmt] http://errors.angularjs.org/1.3.5/ngModel/numfmt?p0=1
check your model: don't using $scope.mymodel = '1';
to use $scope.mymodel = 1;
This directive validate only numbers on input.
angularMainModule.directive('onlyNumbers', function() {
return function(scope, element, attrs) {
var keyCode = [8,9,37,39,48,49,50,51,52,53,54,55,56,57,
96,97,98,99,100,101,102,103,104,105,110];
element.bind("keydown", function(event) {
if($.inArray(event.which,keyCode) == -1) {
scope.$apply(function(){
scope.$eval(attrs.onlyNumbers);
event.preventDefault();`enter code here`
});
event.preventDefault();
}
});
};
});
Upvotes: 1
Reputation: 2274
You can't apply a filter
to ng-model
.
See specifically this answer (not marked as the answer) for more information: https://stackoverflow.com/a/14425022/1452497
Short and sweet:
...the intention of AngularJS inputs and the ngModel directive is that invalid input should never end up in the model. The model should be always valid.
Consider also that the expression inside of ng-model
needs to be assignable from the parser.
ng-model="testA"
eventually breaks down to: testA = some-input-value
This wouldn't work as: testA | number:2 = some-input-value
You should use a formatter
or parser
for this (outside of the view).
Upvotes: 1