【问题标题】:AngularJS compile rendered name value in dynamic formAngularJS以动态形式编译呈现的名称值
【发布时间】:2014-08-22 14:55:25
【问题描述】:

我正在 Angular 中动态构建一个表单。

在我到达我的验证指令之前,一切都很好。

这使用表单对象来获取字段名称并对其应用样式以显示无效字段中的错误。

但是,因为它是动态设置的,所以名称显示为{{field.name}},而不是浏览器中呈现的实际名称。

这是我的标记

<div class="form-group" ng-repeat="field in fields">
    <label class="text control-label col-sm-2" for="{{field.name}}">{{field.label}}</label>
    <div class="input-group col-sm-9" ng-switch="field.type">
        <input ng-switch-when="email" type="email" name="{{field.name}}"  class="form-control" id="{{field.name}}" placeholder="{{field.label}}" ng-model="field.value" required>

        <input ng-switch-when="text" type="text" name="{{field.name}}" class="form-control" id="{{field.name}}" placeholder="{{field.label}}"  ng-model="field.value" required>

        <select ng-switch-when="select" id="{{field.name}}" name="{{field.name}}" id="{{field.name}}" ui-select2="" ng-model="field.value" placeholder="{{field.label}}" required>
            <option></option>
            <option ng-repeat="option in field.options" value="{{option.value}}">{{option.label}}</option>
        </select>

        <p ng-switch-default>Need template for {{field.type}}</p>
    </div>

</div>

这里是我检查指令中的错误的地方

// go through every field
for(var errorType in form.$error)
{
    var fields = form.$error[errorType];
    // loop through all fields of this type
    for(var j = 0 ; j < fields.length ; j++)
    {
        var field = fields[j];
        console.log(field);
        var $field = element.find('[name='+field.$name+']');

        showErrors($field, field, errorType);
    }
}

这里是注销时无效字段之一的属性

...
$invalid: true
$isEmpty: function (value) {
$modelValue: ""
$name: "{{field.name}}"
$parsers: Array[1]
$pristine: true
...

因此,当我尝试使用 var $field = element.find('[name='+field.$name+']'); 获取该字段时,它显然不起作用并且出现错误...

   unrecognized expression: [name={{field.name}}] 

我将如何解决这个问题并获得呈现的名称。我需要这个指令来处理不是动态创建的表单(在这种情况下它可以正常工作)。

【问题讨论】:

标签: angularjs


【解决方案1】:

你必须使用指令:

myApp.directive("dynamicName",function($compile){
  return {
      restrict:"A",
      terminal:true,
      priority:1000,
      link:function(scope,element,attrs){
          element.attr('name', scope.$eval(attrs.dynamicName));
          element.removeAttr("dynamic-name");
          $compile(element)(scope);
      }
   };
});

Here 是个小提琴。

完整答案here。

【讨论】:

  • 仍然不明白终端:true 在指令中的作用......我最好阅读一下。
猜你喜欢
  • 2014-04-24
  • 1970-01-01
  • 2020-03-22
  • 1970-01-01
  • 2014-08-10
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 1970-01-01
相关资源
最近更新 更多