【问题标题】:looping multiple arrays simultaneously with ng-repeat使用 ng-repeat 同时循环多个数组
【发布时间】:2015-08-30 23:59:31
【问题描述】:

我可以在AngularJs 中只使用一个ng-repeat 同时遍历两个数组吗?如果是,那怎么办?

例如我有两个数组

array1 = [1,2,3,4,5]

array2 = [6,7,8,9,10]

它应该能够为两个数组生成相同的索引。

【问题讨论】:

  • 你能澄清你的问题吗

标签: html angularjs


【解决方案1】:

如果你想用第一个数组的索引访问第二个数组,试试这个:

$scope.arr1 = [1, 2, 3, 4, 5]
$scope.arr2 = [6, 7, 8, 9, 10]

<div ng-repeat="number in arr1">
    Number from array1 = {{number}}
    Number from array2 = {{arr2[$index]}}
</div>

看到这个小提琴:http://jsfiddle.net/dm9zhgx9/

【讨论】:

  • 这只适用于这个特定的问题,它不适用于不同长度的数组。
【解决方案2】:

据我所知,Angular 没有实现迭代多个数组的功能。

一种解决方案是连接数组,然后迭代结果。

试试这个:

<div ng-repeat="item in [1,2,3,4,5].concat([6,7,8,9,10])">
    {{item}}
</div>

【讨论】:

  • 如果必须在同一次迭代中访问两个数组的元素,这将无济于事。例如:在同一次迭代中,得到 arr1[0] 和 arr2[0]。
  • @SidharthRamesh 然后看看 Rus Paul 的回答
  • 是的,他的回答有效,但它只适用于问题中的特定示例,对吗?我一直在寻找更通用的方法。
【解决方案3】:

如果您想使用 ngRepeat 组合两个数组,请使用 javascript concat() 函数(AngularJS 允许在 ngRepeat 指令中使用 variable in expression)。

<div ng-repeat="item in array1.concat(array2)">{{item}}</div>

【讨论】:

    【解决方案4】:

    角度

    $http.get("json/timeline.json")
            .then(function(response) {
                var datalen = response.data.tline.length;           
                for (var i=0; i<datalen; i++){
                    vm.eventlist.push(response.data.tline[i]);
                    vm.hpos.push({ 'left' : pos * i + 'px'});
                }
    
            });
    

    HTML

    <li ng-repeat="event in vm.eventlist">
                                <section class="timeline-event past-event" ng-style="{{vm.hpos[$index]}}">
    

    【讨论】:

      猜你喜欢
      • 2015-06-09
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多