Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  139] [ 6]  / answers: 1 / hits: 21466  / 10 Years ago, sat, november 8, 2014, 12:00:00

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();
}
}

More From » angularjs

 Answers
2

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



[#68866] Thursday, November 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ingridmikaylam

Total Points: 93
Total Questions: 81
Total Answers: 105

Location: Nicaragua
Member since Tue, Dec 8, 2020
4 Years ago
;