Angular指令在插入时更改输入值 [英] Angular directive to change input values on insert
问题描述
我想使用如下的cutom指令更改用户输入和模型:
I want to change the user input and model using a cutom directive like:
app.directive('changeInput', function ($parse) {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
//insert logic here
});
}
};
});
因此,用户在任何时候都将char插入:
So any time the user will insert char in:
<input
name="inputText"
type="text"
change-input
data-ng-model="data.name"
>
例如,输入将从'a'变为'b'.我只是需要正确的更改逻辑,我想尝试使用 $ event
和 preventDefault()
,但它会产生更多问题.
The input will change from 'a' to 'b' for example.
I just need the right logic for the change, I hane tried using $event
and preventDefault()
but it created more problams.
谢谢.
推荐答案
您可以在ngModel的解析器和格式化程序中使用build当检测到模型更改时,格式化程序和解析器将启动.用于从模型到视图的更改的数据的格式化程序,以及用于从视图到模型的更改的解析器的数据格式化程序.
You could use build in parsers and formatters of ngModel When a model change is detected the formatter and parser will fire. the formatter for data from a change in the model to the view and parser for a change from the view to the model.
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
});
}
}
};
});
这篇关于Angular指令在插入时更改输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!