Reputation: 1111
I have a view tht has the following requirements:
type
must be number
Now, seting the value programatically as 1.20
for that value to display in the input is complicated:
parseFloat(1.20)
returns 1.2
(1.20).toFixed(2)
returns a string '1.20'
, for which AngularJS fails when attempting to set the valueAny ideas?
Upvotes: 0
Views: 977
Reputation: 1111
Based on https://github.com/angular/angular.js/issues/5680#issuecomment-206325921 I did the following:
(function(){
angular.module('app')
.directive('toFixed', [function () {
return {
require: '^ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$formatters.push(function(value) {
return parseFloat(value);
});
ngModel.$render = function() {
var viewValue = parseFloat(ngModel.$viewValue || 0);
element.val(viewValue.toFixed(2));
}
}
};
}]);
}());
Upvotes: 1
Reputation: 1198
You can take advantage of NgModel and add a parser or formatter.
function NumberFormatter($filter){
'ngInject';
return {
restrict: 'A',
require: '^ngModel',
link: function(scope, element, attrs, ngModelCtrl){
//format text going to user (model to view)
ngModelCtrl.$formatters.push(function(value) {
return $filter('number')(parseFloat(value) , 2);
});
//format text from the user (view to model)
ngModelCtrl.$parsers.push(function(value) {
return doParsing(value)
});
}
}
}
ngModel Formatters and Parsers
Upvotes: 0