ng-model throwing error on input type number in angular 1.3

ak85 picture ak85 · Mar 1, 2015 · Viewed 20.6k times · Source

I have an input field which I want he user to input a number, so I have made an input field with type="number".

When I use it in 1.2 I get no errors

<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

However when I use it in 1.3 I get Error: [ngModel:numfmt] but when i update the number it still seems to get bound to the scope.

<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

Am I doing something wrong here or is this nothing to worry about? I would prefer not to have the errors in my console, when I am trying to debug other issues

Answer

KyleM picture KyleM · Mar 28, 2016

Add this to fix the issue:

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);
                });
            }
        }
    }
}]);