2013-03-08 70 views
0

我有這個分叉代碼plunker分頁它工作正常,但我做了一些調整,使其grub從Json文件中的數據停止工作。
要查看代碼工作註釋行:[13,14,15],然後取消註釋行:[16 - > 37]。
這個錯誤是關於$ filter函數的一個問題,當從Json文件中獲取數據時它返回undefined,所以我認爲是因爲該對象是一個承諾,現在打破了$ filter函數,我不確定。
錯誤發生在這2個功能(使用JSON調用):

$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]); 
    } 
    } 
}; 

錯誤消息:

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)

任何幫助,在此先感謝。

+0

如果'groupToPages'是您所指的「2函數」,那麼我就不會在其中看到任何「Json調用」。另外,你的錯誤信息不在上下文中,所以在這裏沒有任何意義。你可以設置一個運動員嗎? – Stewie 2013-03-08 17:20:20

+0

在第一行中有一個鏈接到我的帖子中的一個蹦牀。 – 2013-03-08 18:17:56

回答

1

問題是過濾器在$ http的promise返回之前被調用,所以items對象是未定義的。
解決方案如Google groups post (proper way to call $filter in the controller?)中所述。
我需要這樣做:

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

所以plunker現在的作品。 感謝谷歌AngularJS組中的Florian Orben。

相關問題