我认为它有以下要求:
type
必须为number
现在,以编程方式将值设置为1.20
以便在输入中显示该值很复杂:
parseFloat(1.20)
返回1.2
(1.20).toFixed(2)
返回字符串'1.20'
,AngularJS在尝试设置值时失败有什么想法吗?
答案 0 :(得分:1)
基于https://github.com/angular/angular.js/issues/5680#issuecomment-206325921,我执行了以下操作:
(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));
}
}
};
}]);
}());
答案 1 :(得分:0)
您可以利用NgModel并添加解析器或格式化程序。
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)
});
}
}
}