在角JS数组 [英] Arrays in Angular JS

查看:112
本文介绍了在角JS数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是新来的角JS,
我推数组中的元素,然后想用NG-重复在HTML中显示。

Am new to angular JS, I am pushing elements in an array and then want to display in the html using ng-repeat.

$scope.groupedMedia = [];

//Adding elements through a for loop.

$scope.groupedMedia[year].push(response.resources[i]);

console.log($scope.groupedMedia);

//The above console displays the following,

//[2014_January: Array[5], 2013_December: Array[95]]

所以在我的HTML,

So in my HTML,

<div ng-repeat="group in groupedMedia">
<div ng-repeat="file in group">
<p>{{file.lastModified}}</p>
</div></div>

我观察到groupedMedia阵列中的HTML是空的,因此不显示任何数据。
我还需要显示阵列中的项目以相同的顺序,因为我推。
要解决这个任何提示会有很大的帮助。

I observe that the groupedMedia array in the html is empty and hence not displaying any data. I also need to display the items in the array in the same order as i push it. Any tips to solve this will be very helpful.

推荐答案

在理想情况下groupedMedia OBJ必须要重组,以一年地图(一年键和资源的价值)。使用随机数的数组,不推荐并必须避免
样品JS:

Ideally groupedMedia obj has to be restructured to an year map(year as key and resources as value). Using an array for random numbers is not recommended and has to be avoided Sample JS:

$scope.groupedMedia = {};    
$scope.groupedMedia[year] = response.resources[i];    
console.log($scope.groupedMedia); //This will provide an output like below.
//{'2014_January': Array[5], '2013_December': Array[95]}

在HTML中,
第一次迭代会虽然groupMedia地图。随着NG-重复可以通过地图迭代,并参照键/值对地图中的子列表。
而第二个则在资源数组。

In html, First iteration will be though the groupMedia map. With ng-repeat one can iterate through a map and refer the key/value pair of the map in the child list. And the second one will the the resources array.

样本HTML code:

Sample HTML code:

<div ng-repeat="(group, files) in groupedMedia">
  <div ng-repeat="file in files">
    <p>{{file.name + ':  '+ file.lastModified}}</p>
  </div>
</div>

已经找到一种方法来保持地图的顺序,

have found a way to maintain the order of the map,


  • 通过按键阵列第一迭代( Object.keys(图))。

  • 然后,使用该值可以采取的关键。

JS另外:

    $scope.groupKeys = function(data){
      return Object.keys(data);
    }

HTML另外:

HTML addition:

<div ng-repeat="key in groupKeys(groupedMedia)">
    {{key}}
    <div ng-repeat="file in groupedMedia[key]">
      <p>{{file.name + ':  '+ file.lastModified}}</p>
    </div>
  </div>

我有更新plunker以反映相同。虽然将是非常有兴趣知道,如果有一个替代方法。
示例演示: http://plnkr.co/edit/JfqIoZMQmFz2cwFvce2K?p=$p$ PVIEW
以上plunker具有与上述code演示。看看,让我知道如果它帮助。

I have update the plunker to reflect the same. Though would be really interested to know if there is an alternate way. Sample Demo: http://plnkr.co/edit/JfqIoZMQmFz2cwFvce2K?p=preview The above plunker has a demo with the above code. Have a look and let me know if it helps.

这篇关于在角JS数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆