作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试创建一个名为 currency
的指令,它在输入的文本之前附加一个 $
。美元符号应始终显示且不可删除。
这是我的代码:
app.directive('currency', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attrs, controller) {
// view -> model
controller.$parsers.push(function (viewValue) {
viewValue = viewValue.replace(/^\$/, '');
controller.$viewValue = viewValue;
return viewValue;
});
// model -> view
controller.$formatters.push(function (modelValue) {
modelValue = '$' + modelValue;
controller.$modelValue = modelValue;
return modelValue;
});
}
};
});
工作示例:https://jsfiddle.net/U3pVM/29012/
如您所见,美元符号最初是附加的,但可以删除并且之后不会附加。似乎我推送到 $formatters
的函数只被调用了一次。它应该像那样工作还是我错过了什么?我怎样才能实现所需的行为?
最佳答案
好的,我已经尝试了一种解决方法,它有效,但我不确定这是否是正确的方法。
更新 fiddle :https://jsfiddle.net/U3pVM/29014/
controller.$parsers.push(function (viewValue) {
//console.log(viewValue.substring(0,1));
if(viewValue.substring(0,1) != "$"){
var view_value = "$" + viewValue;
controller.$setViewValue(view_value);
controller.$render();
}
viewValue = viewValue.replace(/^\$/, '');
//controller.$viewValue = viewValue;
console.log(viewValue);
return viewValue;
});
P.S:我不确定为什么要在 link
函数中将 ngModel
作为 controller
注入(inject)。这可能是一个错误。
关于javascript - $parsers 和 $formatters 只被调用一次,而不是在每次值更新时调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41258125/
我是一名优秀的程序员,十分优秀!