如何跨控制器向AngularJS中的所有输入元素动态添加指令模块 [英] How to dynamically add a directive to all input elements in AngularJS across controllers & modules
问题描述
我想动态地向我所有控制器中的所有文本框添加一个指令 &形式.我从这里得到了一个黑客:如何在 AngularJS 中为输入元素动态添加指令
I want to add a directive dynamically to all my textboxes in all my controllers & forms. I got a hack from here : How to dynamically add a directive to an input element in AngularJS
但就我而言:大约有 200 多个表单分布在不同的控制器和模块和在任何地方添加它会非常耗时.
but in my case: there are around 200+ forms spread across different controllers & modules & it will be very time consuming to add it everywhere.
有没有更简单或更优雅的方法来做到这一点?
Is there an easier or more elegant way to do it ?
我想做什么?我想删除所有领先的 &用户在所有输入框中输入的尾随空格.
What I want to do ? I want to remove all leading & trailing spaces entered by user in all input boxes.
推荐答案
Angular 可以有多个同名指令,并将它们全部应用于元素.创建另一个具有所需行为的 input
指令(demo):
Angular can have multiple directives with the same name, and will apply them all to the element. Create another input
directive with the desired behavior (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();
});
}
}
});
这篇关于如何跨控制器向AngularJS中的所有输入元素动态添加指令模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!