2016-03-23 34 views
0

Webアプリケーションでは、いくつかの要素を含む2つのボックスがあります。私はまた、フィルタ(選択によって構成された)を別に持っています。最初はフィルターがすべて選択され、機能します。しかし、最初のリストで何も見つからないが、2番目のリストにデータがある組み合わせを試すと、エラーが発生します。角度ヌルのプロパティを読み取ることができません

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

私が書くことを試みてきました: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); 
    } 
} 
関連する問題