在嵌套的ng-repeat中使用ng-repeat变量的Angular

时间:2015-03-20 16:47:48

标签: angularjs ng-repeat

我有一个ng-repeat,它遍历一系列值:

var englishList = ["abo", "ser", "vol", "con", "giv", "blo"];
$scope.englishList = englishList;

有没有办法在ng-repeat中循环这些值并将返回的值用作嵌套ng-repeat的一部分?

  <div ng-repeat="api in englishList">
    <div ng-repeat="result in searchData.abo | filter:searchText">
      <li>{{result.title}} {{result.shortname}}</li>
    </div>
 </div>

理想情况下,我希望此行插入$ scope.englishList中的每个ng-repeat值:

<div ng-repeat="result in searchData.{{api}} | filter:searchText">

有没有办法以角度来做这个?

2 个答案:

答案 0 :(得分:3)

你应该能够做到这样的事情,当然:

<div ng-repeat='api in englishList'>
  <div ng-repeat='item in searchData[api]'>
    <!-- uses the value of 'api' as a key in 'searchData' -->
    <!-- you do not need to use interpolation here as these are already expressions -->
  </div>
</div>

我无法给出完整的示例,因为您的代码在如何使用嵌套类型方面并不十分明显,但上面的代码段应该让您了解如何使用嵌套重复。

我建议你使用像这样的对象模型

{ "api": {
  "foo": [ "bar", "baz", "qux" ]
}}

而不是拥有两个不同的数组。这应该使它不那么脆弱。请记住,您的视图逻辑应该尽可能简单,并且不应该对提供给它的数据进行大量操作。我会说迭代一个数组然后使用数组1的值迭代另一个数组作为数组2的键可能对于视图来说有点太多了。

答案 1 :(得分:0)

只需使用括号表示法动态访问属性:

<div ng-repeat="api in englishList">
    <div ng-repeat="result in searchData[api] | filter: searchText" >
        <li>{{result.title}}, {{result.shortname}}</li>
    </div>
</div>

代码段:

angular.module('demoApp', []).controller('DemoController', function ($scope) {

    $scope.englishList = ["abo", "ser", "vol", "con"];;

    $scope.searchData = {
        abo: [{
            title: 'title abo',
            shortname: 'shortname abo'
        }],
        ser: [{
            title: 'title ser 1',
            shortname: 'shortname ser 1'
        }, {
            title: 'title ser 2',
            shortname: 'shortname ser 2'
        }],
        vol: [{
            title: 'title vol',
            shortname: 'shortname vol'
        }],
        con: [{
            title: 'title con',
            shortname: 'shortname con'
        }]
    };
});
p {
    font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="DemoController">
    <div>Search <input type="text" ng-model="searchText"/></div>
    <div ng-repeat="api in englishList">
        <p>{{api}}</p>
        <div ng-repeat="result in searchData[api] | filter: searchText" >
            <li>{{result.title}}, {{result.shortname}}</li>
        </div>
    </div>
</div>

相关问题