Error: [ngModel:numfmt] Expected `22323` to be a number http://errors.angularjs.org/1.5.0/ngModel/numfmt in angular js

Today i am facing a very strange problem in angular js. Actually i am working on a form there a many different types of input like text, number, radio , select etc.
I am also putting an input  type="number" to store only numeric values like below. 

Below is my html code :

<div class="control-group">
<label for="postcode" class="control-label">Post Code</label>
<div class="controls">
<input type="number" class="span4" placeholder="postcode" ng-model="company.postcode" ng-required="true">
<a class="req">*</a>
</div>
</div>


So far every thing is working fine but after saving record i am going to edit page to edit the same record of this input i shown an error i.e "Error: [ngModel:numfmt] Expected `22323` to be a number http://errors.angularjs.org/1.5.0/ngModel/numfmt?p0=22323" in the inspecter and nothing is shown in my input field like below :


Error: [ngModel:numfmt] Expected `22323` to be a number


Solution of this : Actually the problem is that when you get the data from database and trying to display in input type="number" field angular not able to parse it into integer. So its display error. So you have to parse(convert) it into integer and then send it to the input type="number" field to show it. 

Below is the simple directive to solve your problem:

.directive('stringToNumber', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.push(function(value) {
        return '' + value;
      });
      ngModel.$formatters.push(function(value) {
        return parseFloat(value, 10);
      });
    }
  };
});

Now when you are using input type="number" field then you have to call this directive to parse data of that input into integer like below:

<div class="control-group">
<label for="email" class="control-label">Post Code</label>
<div class="controls">
<input type="number" class="span4" placeholder="postcode" ng-model="company.postcode" ng-required="true" string-to-number>
<a class="req">*</a>
</div>
</div>

If you still having any problem or you like this post don't forget leave a comment.

Chear 
Happy Coding :)

Post a Comment

Previous Post Next Post