我想向所有 Controller 和表单中的所有文本框动态添加指令。 我从这里得到了一个黑客:How to dynamically add a directive to an input element in AngularJS
但就我而言:大约有 200 多个表单分布在不同的 Controller 和模块中,将其添加到各处将非常耗时。
有没有更简单或更优雅的方法来做到这一点?
编辑:我想做什么? 我想删除用户在所有输入框中输入的所有前导和尾随空格。
最佳答案
Angular 可以有多个同名指令,并将它们全部应用于元素。创建另一个具有所需行为的 input
指令 ( demo ):
.directive('input', function($compile) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, elem, attrs, ngModel) {
if (!ngModel) {
return;
}
ngModel.$parsers.push(function(value) {
return value.trim();
});
}
}
});
关于javascript - 如何跨 Controller 和模块动态地将指令添加到 AngularJS 中的所有输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40080299/