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. How can this be achieved?
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
<li ng-repeat="name in nameLog | limitTo:-5 | orderBy:'time':true">...</li>
From documentation:
limit: The length of the returned array or string. 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