【问题标题】:ng-repeat dynamic array nameng-repeat 动态数组名
【发布时间】:2015-07-22 22:55:20
【问题描述】:

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

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

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

提前致谢。

【问题讨论】:

  • 你能提供更多代码吗?你在哪里有friends1,friends2
  • 将friends1、friends2等放在一个数组中,然后嵌套ng-repeats,一个在另一个里面怎么样?
  • 你可以像friends[$index]一样使用数组friends

标签: javascript arrays angularjs angularjs-ng-repeat


【解决方案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
    });

【讨论】:

  • 好吧,如果我想组合 2 个字符串值,我该怎么办?例如ng-repeat = "a in (name + 'List')"。此表达式中的名称字符串值。 JonnyListhenryList。我该怎么做?
【解决方案2】:

你可以这样做。

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

【讨论】:

    猜你喜欢
    • 2015-01-11
    • 2015-08-09
    • 2017-08-11
    • 1970-01-01
    • 2016-04-01
    • 2016-05-26
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多