我想使用以下自定义指令更改用户输入和模型:
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”。
我只需要正确的更改逻辑,我尝试使用 $event
和 preventDefault()
但它产生了更多问题。
谢谢。
最佳答案
您可以使用 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/