AngularJS limitTo by last 2 records

别说谁变了你拦得住时间么 提交于 2019-12-08 21:04:02

问题


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


回答1:


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">



回答2:


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


来源:https://stackoverflow.com/questions/11943130/angularjs-limitto-by-last-2-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!