AngularJS Load N at a time
This controller could be used in mobile device when you want to restrict server calls. You pull down a dataset (note this is not for big datasets) but don't want to display all at once. At the same time, having a complicated paging control is undesirable.
by dandoyon
HTML
<script src="http://docs-next.angularjs.org/angular-1.0.0rc2.min.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<div ng:app="MyModule">
<div ng-controller="Ctrl">
Model Size: <input ng-model="modelSize" ng-change="updateModel()"/> (hit tab)<br/>
Search: <input ng-model="searchText" ng-model-instant ng-change="refresh()"/><br/>
I have {{master.length}} friends (showing {{friends.length}}). They are:
<ul>
<li ng-repeat="friend in friends">
[{{$index + 1}}] {{friend.name}}
</li>
</ul>
<button ng-show="cnt < modelSize" ng-click="increaseLimit()">Load {{loadcnt}} more</button>
</div>
</div>
CSS
.ng-invalid { border: 1px solid red; }
body { font-family: Arial,Helvetica,sans-serif; }
body, td, th { font-size: 14px; margin: 0; }
table { border-collapse: separate; border-spacing: 2px; display: table; margin-bottom: 0; margin-top: 0; -moz-box-sizing: border-box; text-indent: 0; }
a:link, a:visited, a:hover { color: #5D6DB6; text-decoration: none; }
.error { color: red; }
JavaScript
angular.module('MyModule', [], function($provide) {
$provide.factory('friendsSvc', [ function() {
var namelist = ['Homer','Hermione','Voldermort','Raj','Mary','Ben','Jen'];
return function(cnt) {
var friends = [];
var mod = namelist.length;
for(i = 0; i < cnt; i++) {
friends.push({ name: namelist[i%mod] + i });
}
return friends;
};
}]);
});
function Ctrl($scope, $filter, friendsSvc) {
$scope.modelSize = 200;
$scope.master = [];
$scope.cnt = 0;
$scope.loadcnt = 15;
$scope.refresh = function() {
// first filter by search term, then subset by cnt
$scope.friends = _.first($filter('filter')($scope.master,$scope.searchText),$scope.cnt);
}
$scope.updateModel = function() {
console.log("updatingModel");
$scope.master = friendsSvc($scope.modelSize);
$scope.refresh();
};
$scope.increaseLimit = function() {
$scope.cnt += $scope.loadcnt;
$scope.refresh();
}
var init = function() {
$scope.updateModel();
$scope.increaseLimit();
};
init();
}
Ctrl.inject = ['$filter','friendsSvc'];