我怎样才能自动添加标签输入字段?
我正在与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>
如果我可以写一个标签
<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;
        },
    };
});
在Stack Overflow上,有许多关于创建自定义输入字段的问题,但他们关心的是数据绑定,自定义格式或绑定到ng-repeat。
然而,我的方法有一个不同的问题:当数据绑定正常工作时,当输入字段为'required'时,Angular的集成表单验证模块会感到困惑。 出于某种原因,验证不会识别新的输入字段,而是由于某些空引用(它具有空值)而使表单无效。 请看最小的例子。
死亡参考来自哪里? 我如何更新验证模块的参考? 有没有更好的方法来实现我的总体目标?
required="required"的表单required="required"修复 transclude=true会在编译阶段后使用元素的副本,我认为这会保持所需的属性不被设置 ng-model ,它不会从你的div中删除,因为tattrs的名字是ngModel (尽管从div中删除并不能删除优先级) http://plnkr.co/edit/5bg8ewYSAr2ka9rH1pfE?p=preview
  我所做的只是将required属性更改为required="required" ,并将这两行添加到指令声明中: 
  transclude: true,
  priority: 10,
  我把ng-transclude放在模板标签上,这样你的元素的内容就会放在标签中,而且你不必为此添加属性。 
上一篇: How can I automatically add labels to input fields?
下一篇: Spring Security and nested FilterChainProxy writing SAML Service Provider
