Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS limitTo by last 2 records

Can a combination of AngularJS filter, order, or limitTo for ng-repeat mimic the _.last in UnderscoreJS?

like image 849
phteven Avatar asked Aug 13 '12 22:08

phteven


2 Answers

Gloopy's answer is correct, but just a note... If you want to use Underscore, you can:

myApp.run(function($rootScope) {
  $rootScope._ = _;
});

<div ng-repeat="item in _.last(items)">
like image 166
Andrew Joslin Avatar answered Oct 21 '22 04:10

Andrew Joslin


If I'm understanding your question correctly I think this fiddle would do it.

For this data:

$scope.items = [{sort: 1, name: 'First'}, 
                {sort: 2, name: 'Second'}, 
                {sort: 3, name: 'Third'}, 
                {sort: 4, name:'Last'}];

If you don't want to actually sort the array and just take the last two items of the array as is (like underscore's last) you can try a negative limit (this would show Third, Last):

<div ng-repeat="item in items | limitTo:-2">

Also note you can chain the filters together like this example sorting the data in reverse and taking 2 items (this would show Last, Third):

<div ng-repeat="item in items | orderBy:'sort':true | limitTo:2">
like image 38
Gloopy Avatar answered Oct 21 '22 04:10

Gloopy