Alexander Kundurdjiev
Alexander Kundurdjiev

Reputation: 85

ng-repeat dynamic array name

Is it possible to achieve dynamic array name, something like friends+$index. For example:

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

The aim is to loop through different arrays: friends1 & friends2. I tried everything, any combination, but without success. I also never came across to appropriate answers.

Thanks in advance.

Upvotes: 3

Views: 1703

Answers (2)

Pedro Mestre Silva
Pedro Mestre Silva

Reputation: 154

Here's another solution:

The 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
    });

Upvotes: 1

jad-panda
jad-panda

Reputation: 2547

You can do something like this.

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"
                ]
            }  
        };
    });

Upvotes: 1

Related Questions