我有分页工作here
但是我想更改数据以使用我正在创建的API数据,但是我收到了错误,我不确定原因。
这是错误:
TypeError: Cannot read property 'then' of undefined
这是代码:
angular.module('cbuiRouterApp')
.controller('BrowseCtrl', function ($scope, $http, socket) {
$scope.itemData = [];
$http.get('/api/items').success(function(itemData) {
$scope.itemData = recipeData;
socket.syncUpdates('Item', $scope.itemData);
});
$scope.predicate = '-created_at';
$scope.totalItems = $scope.itemData.length;
$scope.itemsPerPage = 21
$scope.currentPage = 1;
$scope.maxSize = 5;
$scope.pageCount = function () {
return Math.ceil($scope.itemData.length / $scope.itemsPerPage);
};
$scope.itemData.$promise.then(function () {
$scope.totalItems = $scope.itemData.length;
$scope.$watch('currentPage + itemsPerPage', function() {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
end = begin + $scope.itemsPerPage;
$scope.filteredItems = $scope.itemData.slice(begin, end);
});
});
});
答案 0 :(得分:1)
$http.get('/api/items')
会返回一个承诺,但itemData没有承诺,因此您无法在其上调用$promise.then
。如果您希望在itemData加载后运行该代码,为什么不将它放在success
回调中。 e.g:
angular.module('cbuiRouterApp')
.controller('BrowseCtrl', function ($scope, $http, socket) {
$scope.itemData = [];
$http.get('/api/items').success(function(itemData) {
$scope.itemData = recipeData;
socket.syncUpdates('Item', $scope.itemData);
//Moved to here
$scope.totalItems = $scope.itemData.length;
$scope.$watch('currentPage + itemsPerPage', function() {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
end = begin + $scope.itemsPerPage;
$scope.filteredItems = $scope.itemData.slice(begin, end);
});
});
$scope.predicate = '-created_at';
$scope.totalItems = $scope.itemData.length;
$scope.itemsPerPage = 21
$scope.currentPage = 1;
$scope.maxSize = 5;
$scope.pageCount = function () {
return Math.ceil($scope.itemData.length / $scope.itemsPerPage);
};
});
答案 1 :(得分:0)
什么是recipeData
?
首先设置$scope.itemData = [];
,然后在$ http返回值后,设置$scope.itemData = recipeData;
,这是未定义的。
当然,也不是Array,也不是undefined没有$promise
财产。
基本上你是在尝试[].$promise.then()
,因为你在$ http结束之前就已经这样做了。
不确定你想要实现的目标..
也许像
$http.get('/api/items').$promise.then(function (itemData) {
$scope.itemData = itemData;
socket.syncUpdates('Item', $scope.itemData);
$scope.totalItems = $scope.itemData.length;
$scope.$watchCollection('[currentPage, itemsPerPage]', function() {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
end = begin + $scope.itemsPerPage;
$scope.filteredItems = $scope.itemData.slice(begin, end);
});
});