I'm building a simple app that loads a json
file and presents the content onto the screen and enables the user to scroll through pages using a simple pagination mechanism. I read here and tried to implement a dynamic retrieval of data using a real json
hosted online using a dedicated service. The data loads fine but I'm getting an error: Cannot read property 'slice' of undefined
.
JSfiddle here
The code: Html:
<div ng-controller="MyCtrl">
<ul>
<li ng-repeat="item in catalogData | startFrom:currentPage*pageSize | limitTo:pageSize">
{{item}}
</li>
</ul>
<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
Previous
</button>
{{currentPage+1}}/{{numberOfPages()}}
<button ng-disabled="currentPage >= data.length/pageSize - 1" ng-click="currentPage=currentPage+1">
Next
</button>
</div>
Controller:
function MyCtrl($scope, dataService) {
$scope.currentPage = 0;
$scope.pageSize = 4;
dataService.getData().then(function(data) {
$scope.catalogData = data;
$scope.numberOfPages = function() {
return Math.ceil($scope.catalogData.length / $scope.pageSize);
};
});
}
Get data service:
app.service("dataService", function($http) {
this.getData = function() {
return $http({
method: 'GET',
url: 'https://api.myjson.com/bins/llzg3',
}).then(function(data) {
return data.data;
});
};
});
The filter:
app.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});