Reputation: 1853
I am trying to bind a value which of type string
when it comes from the controller
in a numeric input
field like the following:
<input type="number" ng-model="detail.Value">
Since the detail.Value
is of type string
, I value is not getting displayed (I guess).
I can not change the Value property's type to int.
What can I do in the view to display the value in the number box?
Upvotes: 0
Views: 1393
Reputation: 754
Here is a small directive to force the model value to be a number
function forceNumber ($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
var getter = $parse(attrs.ngModel);
var setter = getter.assign;
var remListner = attrs.$observe('ngModel', function (val) {
var value = getter(scope);
if (typeof value !== 'number') {
setter(scope,+value);
}
// remove listner, no need to keep watching!
remListner();
});
}
};
}
you can see it in action in this small plunker
Hope this helps you, Regards Sander
Upvotes: 1
Reputation: 447
You can either to pass that value to the method on a controller which will do the parsing (and assigning to the model) or if you really want to do that in HTML you can assign parsing method to the scope in the controller ($scope.parseFloat = parseFloat;
) and than parse in ng-init
. Something like this: ng-init="value = parseFloat(detail.Value)"
and then ng-model="value"
.
Upvotes: 1
Reputation: 21901
$scope.isNumeric = function isNumber(number) { // function to test the data can be convert to numeric
return !isNaN(parseFloat(number)) && isFinite(number);
}
...success(data) { // after getting the data from serverside
var formData = data.formDataWithNumeric; // get the form data
for (key in formData) { //iterate through the data
var isNumericData = $scope.isNumeric(formData[key]); // check data can be convert to a numeric
if(isNumericData) {
formData[key] = Number(formData[key]); // reassign the numeric value instead of string value
}
}
}
you can try something like this
Upvotes: 1
Reputation: 77904
Wrap it with parseFloat
:
detail.Value = parseFloat(detail.Value);
Demo Fiddle
Upvotes: 1