2016-03-23 70 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); 
    } 
} 
相关问题