0

我在这里工作的分页

但是我想更改数据以使用我正在创建的 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);
      });
    });
  });
4

2 回答 2

1

$http.get('/api/items')返回一个承诺,但 itemData 没有承诺,因此您无法调用$promise.then它。如果您希望该代码在 itemData 加载后运行,为什么不将它放在success回调中。例如:

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);
    };
  });
于 2014-07-09T14:23:43.757 回答
0

是什么recipeData?一开始你 set $scope.itemData = [];,然后在 $http 返回一个值之后,你 set $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);
    });
});

?

于 2014-07-09T13:51:06.610 回答