【问题标题】:what is the best way to generate DOM elements dynamically with single ng-repeat in angular js在 Angular js 中使用单个 ng-repeat 动态生成 DOM 元素的最佳方法是什么
【发布时间】:2016-09-29 11:13:08
【问题描述】:

<div class="col-lg-6" ng-repeat="controls in steps.infos">
      <div class="form-group">
          <label class="control-label" for="store_list">{{controls.label}}</label>
          <input type="{{controls.type}}" class="form-control input-lg mandatory" id="{{controls.id}}" ng-model="formData[controls.id]" value="{{controls.value}}" name="control_{{controls.id}}" ngRequired="{{controls.mandatory}}">
      </div>
  </div>

上面是我的代码,只有当它是输入字段时,我才动态生成 dom 元素。

我也想生成其他类型的输入字段。比如选择框。 有什么办法可以通过使用指令或其他东西来实现这一点。 DOM 元素不是按顺序排列的,有些可能会被输入,有些可能会被选中,然后可能会再次出现输入框。

请帮忙解决一下

谢谢

【问题讨论】:

  • 您可以创建一个指令,您可以在其中根据controls.type插入模板
  • 如果值被输入那么它应该呈现输入字段,如果值被选择那么它应该在 ng-repeat 中呈现选择吗?

标签: angularjs


【解决方案1】:

您可以创建一个指令,将您的控件作为输入并相应地修改模板。

类似

Customizing the template within a Directive

编辑:

<div ng-repeat="content in vm.contents">

  <form-el formId="content.id"
           type="content.type"
           label="content.label"
           name="content.label"
           data="content.data"
    ></form-el>
</div>

指令::

 .directive('formEl', function () {
    return {
      restrict: 'E',
      compile: function(element, attrs) {
        var type = attrs.type || 'text';
        var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
        if(type=='text'){
          var htmlText = '<div class="control-group">' +
            '<label class="control-label" for="' + attrs.formId +   '">' + attrs.label + '</label>' +
            '<div class="controls">' +
            '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.name + '" ' + required + '>' +
            '</div>' +
            '</div>';
        } else if(type=='radio'){
          var htmlText = '<div class="control-group">' +
            '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
            '<div class="controls">';
          for(var i in attrs.data){
            htmlText=htmlText+'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.name + '" ' + required + '>';
          }
          htmlText=htmlText + '</div>' +  '</div>';
        } else if(type=='selectoption'){
          //add html for radio button
        }
        element.replaceWith(htmlText);
      }
    };
  });

【讨论】:

  • 这篇文章创建的内容与我在 html 中使用 ng-repeat 所做的相同。如何识别它是哪种类型并相应地应用指令
  • 不发送指令中的类型并在那里使用该类型来修改模板
  • 我添加了一个代码 sn-p 指令,您可以针对不同的输入类型对其进行修改
  • 但是如果它是一个选择框,我如何传递选项以及如何处理诸如性别之类的单选按钮
  • 我已经为单选按钮添加了一个示例您只需将数据传递给指令并使用它来创建 html 这可能无法完美运行,因为我只是在没有测试的情况下添加了它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多