Forms 如何将标签自动添加到输入字段?
我正在和AngularJS一起做一个更大的项目。因此,我想使单一形式的工作尽可能容易。由于我们也在使用引导,表单中单个输入字段的代码非常冗长,可能类似于Forms 如何将标签自动添加到输入字段?,forms,validation,angularjs,angularjs-directive,Forms,Validation,Angularjs,Angularjs Directive,我正在和AngularJS一起做一个更大的项目。因此,我想使单一形式的工作尽可能容易。由于我们也在使用引导,表单中单个输入字段的代码非常冗长,可能类似于 <div class="control-group"> <label class="control-label" for="inputEmail">Email</label> <div class="controls"> <input type="text" id="inpu
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<input type="text" id="inputEmail" placeholder="Email">
</div>
</div>
电子邮件
如果我能写一个标签,比如
<custom-input
label="Email"
name="inputEmail"
placeholder="Email"
type="text"
... >
</custom-input>
相反,这将有助于保持代码的整洁和工作的简单
为了实现这一点,我正在开发一个定制的AngularJS指令。我的指令当前使用一个类似于上面的引导示例的模板,自动将标签分配给输入标记。此外,该指令的编译器函数将所有属性从自定义输入标记移动到实际输入标记,以便于自定义自定义输入标记
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;
},
};
});
app.directive('customInput',function(){
返回{
要求:'ngModel',
限制:'E',
模板:“”
“标签”+
'' +
'',
范围:{
ngModel:“=”,
名称:“@name”,
},
替换:正确,
编译:函数(远程通讯、tAttrs、转置){
var tInput=tElement.find('input');
//将给定的属性移动到“自定义输入”
//到实际输入字段
角度.forEach(tAttrs,函数(值,键){
如果(键字符(0)='$')
返回;
tInput.attr(键、值);
tInput.parent().removeAttr(键);
});
返回;
},
};
});
在堆栈溢出方面,有许多关于创建自定义输入字段的问题,但它们都与或有关
然而,我的方法有一个不同的问题:当数据绑定正常工作时,Angular的集成表单验证模块在输入字段为“必需”时会混淆。由于某些原因,验证无法识别新的输入字段,而是由于某个空值的死引用而使表单保持无效。请看
死亡参照物是从哪里来的?如何更新验证模块的引用?有没有更好的方法来实现我的总体目标
required=“required”
格式可以解决这一问题transclude=true
将在编译阶段后使用元素的副本,我认为这样可以避免设置所需的属性ng model
,该优先级没有从您的div中删除,因为tattrs
中的名称是ngModel
(尽管从div中删除不会消除对优先级的需要)required=“required”
,并将这两行添加到指令声明中:
transclude: true,
priority: 10,
顺便说一下,我在模板标签上添加了
ng transclude
,这样元素的内容就可以放在标签中,而不必为此设置属性。谢谢Jason!如果您不想使用required=“required”
,使用tInput.prop(key,true)
而不是attr
-调用value='
的属性就可以了。对于一个角度(2+)的问题,我很想得到这个答案!