嵌套ng-repeat的深度 - AngularJS

时间:2015-10-19 20:38:31

标签: angularjs nested angularjs-ng-repeat

有没有办法获得嵌套ng-repeats的深度?假设您是否正在迭代未知深度的嵌套对象,如嵌套注释?

1 个答案:

答案 0 :(得分:2)

由于ng-repeat创建了一个新的范围,你可以这样做。

{{$depth = $parent.$depth && $parent.$depth + 1 || 1}}

有关工作示例,请参阅https://jsfiddle.net/crgt25uk/

var app = angular.module('app',[]);
app.controller('ExampleController',function($scope){
  $scope.items = [
        {name:'foo',items:[{name:'foofoo'},{name:'foobar'}]},
        {name:'bar',items:[{name:'barfoo'},{name:'barbar'}]}
    ]
})

你的模板:

<div ng-app="app">
    <div ng-controller="ExampleController">
        <li ng-repeat="item in items">{{$depth = $parent.$depth && $parent.$depth + 1 || 1}}: {{item.name}}
            <ul>
                <li ng-repeat="item in item.items">{{$depth = $parent.$depth && $parent.$depth + 1 || 1}}: {{item.name}}</li>
            </ul>
        </li>
    </div>
</div>