4

I have this 2d array in my controller:

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.

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

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

Thanks

2 Answers 2

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).

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

<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]];
}
Sign up to request clarification or add additional context in comments.

5 Comments

Is this answer no longer accurate? It appears to still work in 1.1.x and 1.2.x and the current 1.3.0 beta and still only uses 1 repeat.
This doesn't work for me either.. version 1.4.8. Any new solution? If you select Angular 1.4.8 in your jsfiddle you will see it does not work anymore
This returns nothing: <div class="item item-body" ng-repeat="ureps in userreports"> <div>{{ureps[ureps.length-1]}}</div> </div> But this does... So userreports is getting the data: <div class="item item-body" ng-repeat="ureps in userreports"> <div>{{ureps.description}}</div> </div>
Simple adding ` ng-show='$last'` on the element that loops (ng-repeat) seems to work.. Fellow student suggested it,no idea where it comes from but does the trick
This works fine in all versions. The example on the other hand does not; for a different reason. In 1.3 and above you have to register the controller on the app, it cannot be done as a global function on the window as the example has it. You may want to see this example where it registers the controller and also does the thing that the answer has: jsfiddle.net/TheSharpieOne/cLHcU/42
2

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

true if the repeated element is last in the iterator.

So the correct syntax is

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

1 Comment

This doesn't work for me in version 1.4.8. Do you know another solution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.