質問

I have this forked code plunker for pagination it was working fine but after I made some adjustment to make it grub the data from a Json file it stop working.
To see code working comment lines: [13, 14, 15], then uncomment lines: [16 -> 37].
The error is about a problem with the $filter function it returns undefined when the data are fetched from a Json file so I think because the object is a promise now that breaks the $filter function, I'm not sure.
The error happens in this 2 function (with the Json call):

$scope.search = function () {
  $scope.filteredItems = $filter('filter')($scope.items, function (item) {
    for(var attr in item) {
      if (searchMatch(item[attr], $scope.query)){
        return true;
      }
    }
    return false;
  });
  // take care of the sorting order
  if ($scope.sortingOrder !== '') {
    $scope.filteredItems = $filter('orderBy')($scope.filteredItems, $scope.sortingOrder, $scope.reverse);
  }
  $scope.currentPage = 0;
  // now group by pages
  $scope.groupToPages();
};
// calculate page in place
$scope.groupToPages = function () {
  $scope.pagedItems = [];
  for (var i = 0; i < $scope.filteredItems.length; i++) {
    if (i % $scope.itemsPerPage === 0) {
      $scope.pagedItems[Math.floor(i / $scope.itemsPerPage)] = [ $scope.filteredItems[i] ];
    } else {
      $scope.pagedItems[Math.floor(i / $scope.itemsPerPage)].push($scope.filteredItems[i]);
    }
  }
};

error message:

TypeError: Cannot read property 'length' of undefined
          at Object.$scope.groupToPages (controllers.js:66:45)
          at Object.$scope.search (controllers.js:61:12)
          at new controllers.MainCtrl (controllers.js:99:10)

Any help thanks in advance.

役に立ちましたか?

解決

The problem was that the filter get called before the promise return from $http is fulfilled so the items object is undefined.
the solution as mentioned in this Google groups post ( proper way to call $filter in the controller? ).
I need to do this:

Items.then(function(data) {
    $scope.items = data;
    //call $scope.search here, instead of calling it on line 100
    $scope.search();
});

so the plunker now works. Thanks to Florian Orben in google AngularJS group.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top