gpt4 book ai didi

javascript - 用于更改插入时输入值的 Angular Directive(指令)

转载 作者:行者123 更新时间:2023-12-03 04:58:27 25 4
gpt4 key购买 nike

我想使用以下自定义指令更改用户输入和模型:

app.directive('changeInput', function ($parse) {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
//insert logic here
});
}
};
});

因此,任何时候用户都会将字符插入:

<input 
name="inputText"
type="text"
change-input
data-ng-model="data.name"
>

例如,输入将从“a”更改为“b”。我只需要正确的更改逻辑,我尝试使用 $eventpreventDefault() 但它产生了更多问题。

谢谢。

最佳答案

您可以使用 ngModel 的内置解析器和格式化程序当检测到模型更改时,格式化程序和解析器将触发。用于从模型到 View 的更改的数据格式化程序和用于从 View 到模型的更改的解析器。

app.directive('changeInput', function() {
return { restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
if(ngModel) { // Don't do anything unless we have a model

ngModel.$parsers.push(function (value) {
//value is a
// 'value' should be your model property
ngModel.$setValidity('value', true);
// sets viewValue

ngModel.$setViewValue(value);

// renders the input with the new viewValue
ngModel.$render()
return "b" // you are changing it to b. so now in your controller the value is b and you can trigger your save function
});

ngModel.$formatters.push(function (value) {
//value is b
return "a" // you are changing it to a. So now in your view it will be changed to a
});

}
}
};
});

关于javascript - 用于更改插入时输入值的 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42339667/

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