Angular - LazyLoad JSON
An example of lazy loading JSON data. One nifty feature - it detects when the end of the data has been reached and displays a notice informing the user.
by mkurzweil
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.3/ui-bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.3/ui-bootstrap-tpls.min.js"></script>
<div class="" ng-controller="LazyLoadCtrl as vm">
<div class="row">
<div class="col-xs-12">
<div class="list-group">
<a href="#" class="list-group-item" ng-repeat="headline in vm.headlines | orderBy: '-published'">
<small class="pull-right">{{::headline.published | formatdate:"MMM dd, yyyy 'at' h:mm a" }}</small>
<h5>{{::headline.title}}</h5>
</a>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 text-center">
<button type="button" class="btn btn-primary" ng-click="vm.getHeadlines(vm.numPerLoad, vm.headlines.length)" ng-if="vm.more">Load {{vm.numPerLoad}} More</button>
<alert type="{{vm.alert.type}}" close="vm.closeAlert()" ng-if="!vm.more && vm.alert != null">{{vm.alert.msg}}</alert>
</div>
</div>
</div>
SCSS
small {
text-align:right;
display:block;
}
h5 {
display:block;
clear:both;
}
JavaScript
var myApp = angular.module('myApp',['ui.bootstrap'])
.controller('LazyLoadCtrl', function($scope, $http) {
var vm = this;
vm.alert = { type: 'warning', msg: 'There are no more results.' };
vm.closeAlert = closeAlert;
vm.headlines = [];
vm.getHeadlines = getHeadlines;
vm.more = true;
vm.numPerLoad = 5;
function closeAlert() {
vm.alert = null;
}
function getHeadlines(limit, offset) {
var limit = limit || vm.numPerLoad;
var offset = offset || 0;
$http.get('https://www.stellarbiotechnologies.com/media/press-releases/json?limit=' + (limit+1) + '&offset=' + offset).then(
function(response){
var data = angular.fromJson(response.data.news);
var i = 0;
if (Object.keys(data).length < limit+1) {
vm.more = false;
}
angular.forEach(data, function(value, key) {
if (i == limit) {
return false;
}
vm.headlines.push(value);
i++;
});
},
function(error){
}
)
}
getHeadlines();
})
.filter('formatdate', [
'$filter', function($filter) {
return function(input, format) {
return $filter('date')(new Date(input), format);
};
}
]);