Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 652
ak85 Avatar asked Mar 01 '15 02:03

ak85


1 Answers

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);
                });
            }
        }
    }
}]);
like image 165
KyleM Avatar answered Sep 19 '22 18:09

KyleM