2

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

1
  • You cannot apply filter on ng-model ng-model needs to be a property on the scope that can be assigned to Commented Jan 5, 2015 at 20:16

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

Comments

1
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();
            }
        });
    };
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.