Reputation: 103
As a work around to not being able to filter inputs without directives I've attempted the following:
On the input ngChange detects a change and runs a function. The input has type="number"
<input type="number"
ng-model="ctrl.met.mass"
ng-change="ctrl.met.update.mass()">
The function updates some other fields, then formats them. In this example I want it to display two decimal points with toFixed(2). This is done with variable = variable.toFixed(2)
ctrl.met.cost = ctrl.met.mass * ctrl.met.price;
ctrl.imp.mass = ctrl.met.mass * 0.0353;
ctrl.imp.cost = ctrl.imp.mass * ctrl.imp.price;
console.log(typeof ctrl.met.mass); // number
ctrl.met.mass = ctrl.met.mass.toFixed(2);
console.log(typeof ctrl.met.mass); //string
But the number isn't formatting as well as I'm receiving this error; note the number at the end of the URL is 29.00, being the desired result. If the number is 12.34 that would be in place of 29.00.
Error: ngModel:numfmt
Model is not of type `number`
But when I run typeof ctrl.met.mass at any point, or any other variable I'm working with, it's telling me it is in fact a number except after .toFixed() has interacted with it.
The same error has occurred with the Angular Number Filter (after injecting), parseInt(), parseFloat(), and toPrecision() (to a precision of 4, to ensure two decimal places for a two digit number).
ctrl.met.mass = $filter("number")(ctrl.met.mass, 2);
ctrl.met.mass = $filter("number")(parseInt/Float/Precision(ctrl.met.mass), 2);
ctrl.met.mass = ctrl.met.mass.toInt/Float
ctrl.met.mass = ctrl.met.mass.Precision(4);
I'm thinking I won't be able to do so this way, and will need to use a directive. Before I try that though, why is this happening and can it be worked around?
edit: It seems what I'm trying is impossible. Upon setting ctrl.met.mass to what was, without a doubt, a number with two decimal places it rejected it in preference for an integer. If anyone knows why this is the case, please share.
Upvotes: 1
Views: 2050
Reputation: 179
you can make a stringToNumber directive to parse string to number, the perfect example of this is shown at below link : https://docs.angularjs.org/error/ngModel/numfmt
Upvotes: 0