[英]angularjs show last 5 items in ng-repeat list
I have a list which logs previous names that I have chosen as shown below. 我有一个列表,记录我选择的先前名称,如下所示。 What I want is for the list to always only show the last 5 results, however what I have at the moment is showing the first 5 in order of time with latest first.
我想要的是列表总是只显示最后5个结果,但是我现在所拥有的是以最新的第一个按顺序显示前5个。 How can this be achieved?
怎么能实现这一目标?
http://jsfiddle.net/sfqo2fn3/1/ http://jsfiddle.net/sfqo2fn3/1/
<div ng-controller="MyCtrl">
<input type="text" ng-model="updatedname" />
<input type="button" value="Change name" ng-click="changeName(updatedname)"/>
<br/>
Hello, {{name}}!
<ul>
<li ng-repeat="name in nameLog | limitTo:5 | orderBy:'time':true">{{name.value}} - {{name.time}}</li>
</ul>
</div>
var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
var _nameLog = [];
var userService = {};
userService.name = "John";
userService.ChangeName = function (value) {
userService.name = value;
};
userService.logName = function (value) {
_nameLog.push ({
"value":value,
"time" :Date.now()
});
};
userService.getNameLog = function(){ return _nameLog; }
return userService;
});
function MyCtrl($scope, UserService) {
$scope.name = UserService.name;
$scope.updatedname="";
$scope.changeName=function(data){
$scope.updateServiceName(data);
}
$scope.updateServiceName = function(name){
UserService.ChangeName(name);
UserService.logName(name);
$scope.name = UserService.name;
$scope.nameLog = UserService.getNameLog();
}
}
You can do: | limitTo: -5
你可以这样做:
| limitTo: -5
| limitTo: -5
<li ng-repeat="name in nameLog | limitTo:-5 | orderBy:'time':true">...</li>
From documentation : 来自文档 :
limit: The length of the returned array or string.
limit:返回的数组或字符串的长度。 If the limit number is positive, limit number of items from the beginning of the source array/string are copied.
如果限制数为正,则复制源数组/字符串开头的限制项数。 If the number is negative, limit number of items from the end of the source array/string are copied.
如果数字为负数,则复制源数组/字符串末尾的限制项数。 The limit will be trimmed if it exceeds array.length
如果限制超过array.length,则将限制该限制
You can create a custom filter for this. 您可以为此创建自定义过滤器。 I have modified your fiddle a little bit:
我已经修改了你的小提琴:
http://jsfiddle.net/sfqo2fn3/2/ http://jsfiddle.net/sfqo2fn3/2/
myApp.filter('slice', function() {
return function(arr, start, end) {
if(!end) {
return (arr || []).slice(start);
}
return (arr || []).slice(start, end);
};
});
You now have a "slice" filter that will filter to only show the last 5 items in the array. 您现在有一个“切片”过滤器,它将过滤以仅显示数组中的最后5个项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.