ng-repeat动态数组名称

时间:2015-05-12 07:35:38

标签: javascript arrays angularjs angularjs-ng-repeat

是否可以实现动态数组名称,例如friends+$index。例如:

ng-repeat="friend in {{'friends'+$index}}"

目的是遍历不同的数组:friends1& friends2。 我尝试了一切,任何组合,但没有成功。我也从来没有得到适当的答案。

提前致谢。

2 个答案:

答案 0 :(得分:1)

你可以这样做。

http://jsfiddle.net/jigardafda/gw7f1qq0/1/

HTML

<div ng-app="myapp">
    <div ng-controller="MyCtrl">
        <div ng-repeat="(name, value) in frndslist">
            {{name}}
            <div ng-repeat="item in value.list">
                {{item}}
            </div>
        </div>
    </div>
 </div>

JS

var myApp = angular.module('myapp',[]);

myApp
    .controller('MyCtrl', function ($scope, $rootScope) {

        $scope.frndslist = {
            'friend1': {
                name: 'x1 frnd',
                list: [
                    "1.some1",
                    "1.some2"
                ]
            },
            'friend2': {
                name: 'x2 frnd',
                list: [
                    "2.some1",
                    "2.some2"
                ]
            }  
        };
    });

答案 1 :(得分:1)

这是另一个解决方案:

HTML:

<div ng-app="App" ng-controller="AppController as controller">
    <ul ng-repeat="friend in friends[index]">
        <li>{{friend}}</li>
    </ul>

</div>

使用Javascript:

    var application = angular.module("App",[]);

    application.controller("AppController",function($scope){
        friends1  =["Name1", "Name2", "Name3", "Name4"];
        friends2  =["Name5", "Name6", "Name7"];
        $scope.friends  = new Array();
        $scope.friends.push(friends1);
        $scope.friends.push(friends2);
        //.......
        $scope.index = 0; // in this example it can be 0 or 1
    });