Thursday, May 5, 2016

AngularJS - numfmt Solution

Now.. Your JSON array returns your "number" values as "string" values. For example, instead of returning you 50, it returns you "5".
While using ng-model inside a text box of type "number", you'll receive a something called "numfmt" error. You can check it here on Angular JS documentation.
The idea is that, AngularJS doesn't provide you a direct solution for it, and asks you as a developer to provide your own "directive" to resolve this issue.
So, what to do.
Easily, use angular.forEach method to parse all the "string" values you're receiving and then convert their type into "number" using Number method.

It should be something like that, assuming you JSON is "result" and your number (string) value is "numStr"



angular.forEach(result, function(value, key) {
    value.numStr = Number(value.numStr);
});


On your view, use ng-init to initialize your model with the "number" typed value resulted from this process. Please do before your <input>, It's better to do.

Cheers

No comments:

Post a Comment