Nil*_*elm 7 forms validation angularjs angularjs-directive
我正在与AngularJS合作开展更大的项目.因此,我希望尽可能简化单个表单的工作.由于我们也使用bootstrap,表单中单个输入字段的代码非常冗长,也许就像
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<input type="text" id="inputEmail" placeholder="Email">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
如果我可以写一个标签,如
<custom-input
label="Email"
name="inputEmail"
placeholder="Email"
type="text"
... >
</custom-input>
Run Code Online (Sandbox Code Playgroud)
相反,这将有助于保持代码清洁和工作简单.
为了实现这个目标,我正在开发一个自定义的AngularJS指令.我的指令当前使用类似于上面的bootstrap示例的模板,自动将标签分配给input-tag.此外,该指令的编译器函数将所有属性从自定义输入标记移动到实际输入标记,以便于自定义自定义输入标记.
app.directive('customInput', function() {
return {
require: 'ngModel',
restrict: 'E',
template: '<div>' +
'<label for="{{ name }}">the label</label>' +
'<input id="{{ name }}" ng-model="ngModel" />' +
'</div>',
scope: {
ngModel: '=',
name: '@name',
},
replace: true,
compile: function (tElement, tAttrs, transclude) {
var tInput = tElement.find('input');
// Move the attributed given to 'custom-input'
// to the real input field
angular.forEach(tAttrs, function(value, key) {
if (key.charAt(0) == '$')
return;
tInput.attr(key, value);
tInput.parent().removeAttr(key);
});
return;
},
};
});
Run Code Online (Sandbox Code Playgroud)
在Stack Overflow上,有很多关于自定义输入字段创建的问题,但它们涉及数据绑定,自定义格式化或绑定到ng-repeat.
然而,我的方法有一个不同的问题:当数据绑定正常工作时,当输入字段为"required"时,Angular的集成表单验证模块会混淆.由于某种原因,验证无法识别新的输入字段,而是由于某些死引用而使表单无效,该引用具有空值.请参阅最小的例子.
死亡参考来自哪里?如何更新验证模块的参考?有没有更好的方法来实现我的总体目标?
required="required"修复了这个问题transclude=true将在编译阶段后使用元素的副本,我认为这可以防止设置所需的属性ng-model,它不会从您的 div 中删除,因为 中的名称tattrs是ngModel(尽管从 div 中删除并不会消除对优先级的需要)http://plnkr.co/edit/5bg8ewYSAr2ka9rH1pfE?p=preview
我所做的就是将 required 属性更改为required="required"并将这两行添加到指令声明中:
transclude: true,
priority: 10,
Run Code Online (Sandbox Code Playgroud)
顺便说一下,我放置ng-transclude了模板标签,因此元素的内容将放入标签中,并且您不必为此拥有属性。