简体   繁体   English

使用Angular ng-repeat获取数组的最后一个索引

[英]Get last index of an array using Angular ng-repeat

I have an Object that I'm iterating over, that contains array values, here's an example (Note that my version has a lot more information than just content ): 我有一个我要遍历的Object ,其中包含数组值,这是一个示例(请注意,我的版本包含的信息远不止content ):

$scope.messages = { "1": [ 
    { "content": "Hello" },
    { "content": "How are you" },
    { "content": "This should be displayed" }
]};

Take this as a "messaging thread" type of scenario, where you would group the threads by a phone number (in this event, 1 ) and then show the last received message (the last index of the array). 将此作为“消息线程”类型的方案,在该方案中,您将通过电话号码(在此事件中为1 )对线程进行分组,然后显示最后收到的消息(数组的最后一个索引)。

Here's what I've tried, but it doesn't work. 这是我尝试过的方法,但是不起作用。

<div ng-repeat="(thread_id, message_data) in messages">
    Thread ID: {{thread_id}} <br>
    Last message: {{message_data[message_data.length - 1].content}}
</div>

The thread id shows, but the message data does not. 显示线程ID,但不显示消息数据。

Hardcoding the value such as: 硬编码值,例如:

{{message_data[0].content}}

works as expected. 如预期般运作。

Before people start suggesting $last please note that $last only returns true or false, depending on if the ng-repeat iteration is on its last cycle. 在人们开始建议$last之前,请注意$last只返回true或false,这取决于ng-repeat迭代是否在其最后一个周期。 Considering I'm using a (key, value) pair, and in my case the array is the value. 考虑到我正在使用(key, value)对,在我的情况下,数组是值。 I need the array length of the value, which value.length does provide. 我需要value.length确实提供的值的数组长度。 In this event: 在这种情况下:

 {{ message_data.length }}

will print out the value of 3 . 将打印出3的值。 However using message_data.length - 1 to obtain a value from the array does not work. 但是,使用message_data.length - 1从数组获取值不起作用。

Add this to your html 将此添加到您的html

ng-init="$last ? getLastIndex($index) : ''"

Js s

$scope.getLastIndex = function (index){
  $scope.lastIndex = index;
}

Then this should work fine 那应该很好

message_data[lastIndex].content

虽然我的确切情况可能并不在所有版本的AngularJS上都存在,但我还是通过在括号内加上数学来解决了该问题。

message_data[(message_data.length - 1)].content

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM