I encountered the error message shown below:
angular.min.js:114TypeError: Cannot read property 'slice' of undefined at templateController.js:28
The issue is due to this line of code:
$scope.filteredTemplates = $scope.templates.slice(begin, end);
Below is my code snippet:
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 working on implementing pagination for an array in $scope.templates
.
To achieve this, I am utilizing the $watch()
method to track the user's current page and appropriately slice the $scope.templates
array based on the selected page.
However, a challenge arises when using a callback within the .success()
method. The callback's execution timing is unknown.
As a result, the $watch()
function executes first and detects that $scope.templates
is undefined. Is there a workaround or solution to ensure the pagination functionality works as intended?