2016-03-23 88 views
0

在Web應用程序中,我有兩個包含一些元素的框。我也有過濾器(由選擇組成)旁邊。在開始時,過濾器全部被選中,並且它起作用。但是當我嘗試在第一個列表中找不到任何內容但在第二個列表中有一些數據的組合時,出現錯誤。這是當我打電話控制器服務:Angular無法讀取null的屬性

if(data){ // If i have some response form serve 

var tmp = null; 
var lastName = null; 

angular.forEach(data.people, function(ppl){ 
if(ppl.lastName != lastName){ 
    if (lastName != null){ 
     $scope.people.push(tmp); 
    } 
    // Clean the tmp 
    tmp = { 
      name : null, 
      count : 0, 
      products : [] 
    }; 
    // Update lastName 
    lastName = ppl.lastName; 
    } 
    // Add the actual row in the ob 
    tmp.name = lastName; 
    tmp.count += ppl.personCount; 
    tmp.products.push(ppl); 
    }); 

    // Process lasts elements (if there are some) in the array 
    if(tmp.products.length > 0){ 
    $scope.people.push(tmp); 
    } 

的錯誤是:Cannot read property 'products' of null

我試着寫:var tmp = [];,而不是空的,但它說Cannot read property 'products' of undefined

+1

使用'if(tmp && tmp.products && tmp.products.length> 0)'進行上一次驗證 –

回答

0

我想angular.forEach給你一個範圍界定問題。改爲嘗試下面的代碼。

if(data && data.people.length > 0){ // If i have some response form serve 

var tmp = {}; 
var lastName = null; 

for(var i = 0; i < data.people.length; i++){ 
    if(ppl.lastName != lastName){ 
     if (lastName != null){ 
      $scope.people.push(tmp); 
     } 
     // Clean the tmp 
     tmp = { 
      name : null, 
      count : 0, 
      products : [] 
     }; 
     // Update lastName 
     lastName = ppl.lastName; 
    } 
    // Add the actual row in the ob 
    tmp.name = lastName; 
    tmp.count += ppl.personCount; 
    tmp.products.push(ppl); 
    }; 

    // Process lasts elements (if there are some) in the array 
    if (tmp && tmp.products && tmp.products.length > 0) 
     $scope.people.push(tmp); 
    } 
} 
相關問題