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