gpt4 book ai didi

javascript - $parsers 和 $formatters 只被调用一次,而不是在每次值更新时调用

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:42:07 26 4
gpt4 key购买 nike

我正在尝试创建一个名为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com