Angularjs shows last 5 items in ng-repeat list

I have a list that registers the previous names that I have selected, as shown below. I want the list to always show only the last 5 results, however, what I have at the moment shows the first 5 in order of time with the last 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(); } } 
+7
javascript angularjs angularjs-ng-repeat
source share
2 answers

You can do: | limitTo: -5 | limitTo: -5

 <li ng-repeat="name in nameLog | limitTo:-5 | orderBy:'time':true">...</li> 

From the documentation :

limit: The length of the returned array or string. If the limit number is positive, the number of copies of the elements from the beginning of the original array / row is copied. If the number is negative, the number of elements from the end of the original array / row is copied. The limit will be truncated if it exceeds array.length

+34
source share

To do this, you can create your own filter. I changed your fiddle a bit:

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

Now you have a β€œslice” filter, which will only filter to display the last 5 elements in the array.

+2
source share

All Articles