我想创建一个指令,它可以对表单中的所有输入字段执行一些很棒的操作。
但是,如果我只能应用该指令一次(对 <form>
本身)而不是让它绑定(bind)到所有 <input>
,我会很高兴。的
我应该如何确定所有表单输入元素?
我看到一些可能的解决方案:
element[0].childNodes // filter all inputs
element[0].children
element[0].elements // seems to contain nothing but the stuff i want
也许我思想封闭,在这里看不到正确的解决方案。
感谢任何帮助和意见
最佳答案
警告:这只是一个在简单示例中有效的想法。我并不是说它是错误的(不过,这是可以讨论的),但我还没有在更复杂的环境中使用过它。
所以...您实际上可以创建第二个 input
指令,并且仅当另一个指令(例如 myDirective
)应用于封闭表单时才应用它。
假设您有 2 个表单:
<body>
<form name="myForm1" ng-controller="MainCtrl">
Name: <input id="name1" type="text" ng-model="data.name" /><br/>
Surname: <input id="surname1" type="text" ng-model="data.surname" />
<pre>{{data}}</pre>
</form>
<br/>
<form name="myForm2" ng-controller="MainCtrl" my-directive>
Name: <input id="name2" type="text" ng-model="data.name" /><br/>
Surname: <input id="surname2" type="text" ng-model="data.surname" />
<pre>{{data}}</pre>
</form>
</body>
只有第二种形式用my-directive
标记。现在,您的指令可能如下所示:
app.directive("myDirective", function(){
return {
restrict: 'A',
require: ['form'],
controller: function() {
// nothing here
},
link: function(scope, ele, attrs, controllers){
var formCtrl = controllers[0];
console.log("myDirective applied to form:", formCtrl.$name);
}
};
});
app.directive("input", function(){
return {
restrict: 'E',
priority: -1000,
require: '^?myDirective',
link: function(scope, ele, attrs, ctrl){
if (ctrl) {
console.log("applying custom behaviour to input: ", ele.attr('id'));
// ... awesomeness here
}
}
};
});
查看live并查看日志。原始的 input
指令与您自己的指令并存。证明这一点的证据是表单仍然有效(当您键入时,模型会更新:这是 input
的工作,然后是 ngModel
的工作)。
您的input
指令还可以使用ngModel来操作输入值:
app.directive("input", function(){
return {
restrict: 'E',
priority: -1000,
require: ['?ngModel', '^?myDirective'],
link: function(scope, ele, attrs, ctrls){
var ngModel = ctrls[0];
var myDirective = ctrls[1];
if (myDirective) {
console.log("applying custom behaviour to input: ", ele.attr('id'));
// ... awesomeness here
}
}
};
});
关于angularjs - 如何获取表单中的所有输入字段(AngularJS 指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19831252/