嵌套的ng-repeat无法正常工作

时间:2018-07-31 14:02:45

标签: html angularjs angularjs-directive angularjs-ng-repeat

我有以下代码

<div class="list-group">
   <a class="list-group-item" href="" ng-repeat="q in data.items">
     <i ng-if="q.glyph" class="fa fa-{{::q.glyph}} m-r-sm"></i>
     <i ng-if="!q.glyph" class="fa fa-chevron-right m-r-sm"></i> {{::q.label}}</a>

<div>
    <a href="" class="list-group-item" ng-repeat="i in q.items | orderBy:'label'">
      <i class="fa fa-{{::i.glyph}} m-r-sm"></i>
        <i ng-if="::!i.glyph" class=""></i> {{::i.label}}
    </a>
</div>

由于某种原因,第二个ng-repeat i in q.items不会向视图呈现任何内容。但是,我更改了代码(下一个代码段)以再次遍历data.items ,虽然我认为这不是必需的,但它可以工作。第一个代码有什么问题?

<div class="list-group">
   <a class="list-group-item" href="" ng-repeat="q in data.items">
     <i ng-if="q.glyph" class="fa fa-{{::q.glyph}} m-r-sm"></i>
     <i ng-if="!q.glyph" class="fa fa-chevron-right m-r-sm"></i> {{::q.label}}</a>

<div>
  <div ng-repeat="z in data.items">
    <a href="" class="list-group-item" ng-repeat="i in z.items | orderBy:'label'">
      <i class="fa fa-{{::i.glyph}} m-r-sm"></i>
        <i ng-if="::!i.glyph" class=""></i> {{::i.label}}
    </a>
   </div>
</div>

1 个答案:

答案 0 :(得分:4)

第一个代码段不起作用,因为迭代已结束。

  

错误

<a ng-repeat="q in data.items">
  {{q.data}}
</a> <!-- end of iteration -->
<a ng-repeat="i in q.items"> <!-- You try to iterate an undefined array -->
  {{i.data}}
</a>

解决方案可能是:

<div class="list-group">
    <div ng-repeat="q in data.items">
        <a class="list-group-item" href="">
            <i ng-if="q.glyph" class="fa fa-{{::q.glyph}} m-r-sm"></i>
            <i ng-if="!q.glyph" class="fa fa-chevron-right m-r-sm"></i> {{::q.label}}
        </a>
        <div>
            <a href="" class="list-group-item" ng-repeat="i in q.items | orderBy:'label'">
                <i class="fa fa-{{::i.glyph}} m-r-sm"></i>
                <i ng-if="::!i.glyph" class=""></i> {{::i.label}}
            </a>
        </div>
    </div>
</div>