Angular.js获取ng-repeat中2d数组中最后一个元素的索引

时间:2022-08-23 23:28:06

I have this 2d array in my controller:

我的控制器中有这个2d数组:

1 2 6
1 2 7 9
2
1 5 3 2 6

I need to show to the user the last element of each row (example: 6, 9, 2, 6) I think I need to use some combination of directive ng-repeat or get the $last index of the array using angular filters.

我需要向用户显示每一行的最后一个元素(例如:6,9,2,6)我想我需要使用指令ng-repeat的某种组合或使用角度过滤器获取数组的$ last索引。

Here's what I have but doesn't work:

这是我的,但不起作用:

<div ng-repeat="row in array">
 {{row[$last].property}}
</div>

Thanks

谢谢

2 个解决方案

#1


2  

Example: http://jsfiddle.net/TheSharpieOne/cLHcU/
Note in newer version of angular, you have to register the controller instead of throwing it onto the global window object. Here is an example using 1.4: http://jsfiddle.net/TheSharpieOne/cLHcU/42/ (note: the repeat stays the same).

示例:http://jsfiddle.net/TheSharpieOne/cLHcU/请注意,在较新版本的angular中,您必须注册控制器,而不是将其投放到全局窗口对象上。以下是使用1.4的示例:http://jsfiddle.net/TheSharpieOne/cLHcU/42/(注意:重复保持不变)。

HTML/Template: (All the work is done here) No need for a nested repeat.

HTML /模板:(所有工作都在这里完成)不需要嵌套重复。

<span ng-repeat="arr in myArr">
    {{arr[arr.length-1]}}
</span>

Controller: (only has the array)

控制器:(只有数组)

function myCtrl($scope) {
    $scope.myArr = [[1,2,6],[1,2,7,9],[2],[1,5,3,2,6]];
}

#2


2  

As mentioned in ng-repeat documentation $last is a boolean value not an index :

正如在ng-repeat文档中提到的,$ last是一个布尔值而不是索引:

true if the repeated element is last in the iterator.

如果重复元素在迭代器中的最后一个,则返回true。

So the correct syntax is

所以正确的语法是

{{row[row.length-1].property}}

#1


2  

Example: http://jsfiddle.net/TheSharpieOne/cLHcU/
Note in newer version of angular, you have to register the controller instead of throwing it onto the global window object. Here is an example using 1.4: http://jsfiddle.net/TheSharpieOne/cLHcU/42/ (note: the repeat stays the same).

示例:http://jsfiddle.net/TheSharpieOne/cLHcU/请注意,在较新版本的angular中,您必须注册控制器,而不是将其投放到全局窗口对象上。以下是使用1.4的示例:http://jsfiddle.net/TheSharpieOne/cLHcU/42/(注意:重复保持不变)。

HTML/Template: (All the work is done here) No need for a nested repeat.

HTML /模板:(所有工作都在这里完成)不需要嵌套重复。

<span ng-repeat="arr in myArr">
    {{arr[arr.length-1]}}
</span>

Controller: (only has the array)

控制器:(只有数组)

function myCtrl($scope) {
    $scope.myArr = [[1,2,6],[1,2,7,9],[2],[1,5,3,2,6]];
}

#2


2  

As mentioned in ng-repeat documentation $last is a boolean value not an index :

正如在ng-repeat文档中提到的,$ last是一个布尔值而不是索引:

true if the repeated element is last in the iterator.

如果重复元素在迭代器中的最后一个,则返回true。

So the correct syntax is

所以正确的语法是

{{row[row.length-1].property}}