如何根据ng-repeat中的条件添加容器div?

时间:2016-11-28 09:43:20

标签: angularjs

如何根据ng-repeat中的某些条件添加div容器?基本上我想将主容器分成多个部分。以下是代码示例代码:

<div class="content-wrapper">
      <div class="content"
           ng-repeat="metadata in $ctrl.pages"
           ng-class="metadata.page.title">
        <div class='page_section_title' ng-repeat="control in metadata.page.controls | orderBy:'sequence'">   

          //based on type of control - control.type, I want to divide controls into multiple sections - like
          //if(control.type === 'title'){
               <div class='page_title'>
                    <customControl control = 'control'..></customControl>
               </div>
          // } else {
                <div class='page_content'>
                    <customControl control = 'control'..></customControl>
               </div>
         // }
        </div>
      </div>

      <footer></footer>
    </div>

这里我想通过添加容器div来创建单独的控件组。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:2)

<div class="content-wrapper">
      <div class="content"
           ng-repeat="metadata in $ctrl.pages"
           ng-class="metadata.page.title">
        <div class='page_section_title' ng-repeat="control in metadata.page.controls | orderBy:'sequence'">   

          //based on type of control - control.type, I want to divide controls into multiple sections - like
          //if(control.type === 'title'){
               <div class='page_title' ng-if="control.type == 'title'">
                    <customControl control = 'control'..></customControl>
               </div>
          // } else {
                <div class='page_content' ng-if="control.type == 'content'">
                    <customControl control = 'control'..></customControl>
               </div>
         // }
        </div>
      </div>

      <footer></footer>
    </div>

使用ng-if来达到你想要的效果。 只有当条件为真时,才会创建容器,否则不会。

语法:

<element ng-if="expression"></element>

如果'expression'的计算结果为true,则元素将被添加到DOM中,否则将不会。

答案 1 :(得分:1)

最好的方法是使用ng-class来解决问题:

<div ng-class="{'page_title': control.type == 'title', 'page_content': control.type == 'content'}">
     <customControl control = 'control'..></customControl>
</div>

ng-class而不是ng-if的兴趣在于您只有一个div要声明。

在您的完整代码中:

<div class="content-wrapper">
  <div class="content" ng-repeat="metadata in $ctrl.pages">

    <div class='page_section_title' ng-repeat="control in metadata.page.controls | orderBy:'sequence'">
      <div ng-class="{'page_title': control.type == 'title', 'page_content': control.type == 'content'}">
        <customControl control='control' ..></customControl>
      </div>
    </div>

  </div>

  <footer></footer>
</div>

Demo on JSFiddle