ng-model for input type 'number' not working angularjs ng-model for input type 'number' not working angularjs angularjs angularjs

ng-model for input type 'number' not working angularjs


I just ran into this same issue and managed to solve it. In my case, the model is being obtained via a RESTful $resource and the value for the amount is being provided as a string to the field, which in turn wipes out the value. In order to address this, I ended up doing the following in my controller:

$scope.cart = Cart.get(id: $routeParams.id, function(cart){    cart.quantity = parseFloat(cart.quantity, 10);});

which turns the value into a float, prior to updating the view. One gotcha I ran into is that my first attempt was setting $scope.cart.quantity = parseFloat($scope.cart.quantity, 10) immediately after the get. This was not working since the value was overwritten when the async call to get completed.

$scope.cart = Cart.get(id: $routeParams.id);$scope.cart.quantity = parseFloat($scope.cart.quantity, 10); // This won't work

Hope this helps.


Your binded value is a string not a number.

First of all, check that your server is sending a number. If you are using PHP, you might want to use:

json_encode($array, JSON_NUMERIC_CHECK);

You might also turn your string into int or float with Javascript on the client side:

var data = ['1.9', '3']; //these won't be binded to the numbers-only inputdata[0] = parseFloat(data[0]); //this willdata[1] = parseInt(data[1]);

It's not a bug as that the numbers input only accepts valid numbers (hopefully).


Note:

I also tried to bind an ng-value with an integer filter but it wont't work. Maybe because the ng-model is the one that's binded when both are found (yup, they have the same priority level).


I solve this problem using a custom directive:

angular.module('directives').directive('input', function() {  return {    restrict: 'E',    require: 'ngModel',    link: function(scope, $el, attrs, ngModel) {      if ($el.get(0).type === 'number') {        ngModel.$parsers.push(function(value) {          return value.toString();        });        ngModel.$formatters.push(function(value) {          return parseFloat(value, 10);        });      }    }  }})

This way you do not need to change any HTTP response when the data is being obtained via a restfull resource.

Restrict this directive if necessary :)