Reputation: 1279
I'm getting the following error:
angular.min.js:114TypeError: Cannot read property 'slice' of undefined at templateController.js:28
It's because of this line of code:
$scope.filteredTemplates = $scope.templates.slice(begin, end);
And here is my code:
var template = angular.module('TemplateCtrl',['ui.bootstrap']);
template.controller('TemplateController',function($scope, Template){
var getTemplates = Template.all();
$scope.filteredTemplates = [];
$scope.currentPage = 1;
$scope.numPerPage = 10;
$scope.maxSize = 5;
getTemplates.success(function(response){
if(response[0] == 200){
$scope.templates = response[1];
}else{
//user wasn't logged in to view the templates (voorbeeld contracten)
console.log('Please log in');
}
});
$scope.numPages = function () {
return Math.ceil($scope.templates.length / $scope.numPerPage);
};
$scope.$watch('currentPage + numPerPage', function() {
var begin = (($scope.currentPage - 1) * $scope.numPerPage)
, end = begin + $scope.numPerPage;
$scope.filteredTemplates = $scope.templates.slice(begin, end);
});
});
I'm trying to make a pagination for my array in $scope.templates
.
Therefore I'm using the $watch()
method to see on which page the user is. And to slice the array in $scope.templates
depending on which page the user has clicked on.
However I'm using a callback as you see in the .success()
method. And the problem with a callback is that you don't know when it gets executed.
Because of that the $watch()
gets executed first and sees ofcourse that $scope.templates
is undefined.. Gladly I want to ask if someone knows how I can still make this pagination work?
Upvotes: 0
Views: 39
Reputation: 685
looks like your watch is getting executed before the getTemplates getting resolved. So you don't have $scope.templates. Define $scope.template = []; up top and execute slice only if $scope.template.length>0
$scope.templates = [];
$scope.$watch('currentPage + numPerPage', function() {
var begin = (($scope.currentPage - 1) * $scope.numPerPage)
, end = begin + $scope.numPerPage;
if($scope.templates.length>0){
$scope.filteredTemplates = $scope.templates.slice(begin, end);
}
});
Upvotes: 1