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

Angular using ng-repeat variable in nested 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">

angular有没有办法做到这一点?

你应该可以做这样的事情,当然:

<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 的键来迭代另一个数组对于视图来说可能有点太多了。

只需使用括号符号动态访问 属性 :

<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>