【发布时间】:2014-11-18 04:06:52
【问题描述】:
我想要做的就是将我输入的数字自动格式化为 $,因为我在输入中输入它,但将实际模型保留为没有 $ 的数字。我尝试了不同的方式,但我现在所拥有的只是如果我在模型中已经有一些值(而不是 null),它将用 $ 显示。但是,如果它为 null 或者如果我删除输入中的所有内容并从头开始,则这些值不会被格式化为 $ 。我究竟做错了什么? 这是一个jsfiddle
http://jsfiddle.net/rmzqomzz/1/
angular.module('HelloApp', []);
function myTest() {
return {
restrict: 'EA',
require: 'ngModel',
link: function(scope, element, iAttrs, ngModel) {
console.log(iAttrs.myTest);
ngModel.$formatters.push(function(modelValue){
if(!modelValue) return;
if(iAttrs.myTest == 'money'){
return '$ '+modelValue;
}else{
return modelValue +' %';
}
});
ngModel.$parsers.push(function(viewValue){
return viewValue.replace('$', '').trim();
});
scope.$watch(
function(){
return ngModel.$modelValue;
}, function(newValue, oldValue){
console.log('value changed '+ newValue);
}, true
);
}
};
};
angular.module('HelloApp').directive('myTest', myTest);
angular.module('HelloApp').controller('HelloController', function($scope) {
$scope.mon = {'balu':null};
});
谢谢
【问题讨论】:
标签: angularjs angularjs-directive