2017-02-15 7 views
0

各親からの子リストを取得するためにクエリを実行する必要があります。冗長なネストされた子クエリ無限ループ

HTML:

<tr ng-repeat="parent in parents"> 
    <td>{{parent.id}}</td> 
    <td>{{parent.name}}</td> 
    <td> 
     <li ng-repeat="child in getChildren(parent.id)"> 
      {{child}} 
     </li> 
    </td> 
</tr> 

JS:

app.controller('mainCtrl', function($scope, Restangular) { 
... 
$scope.getChildren = function(parentId) { 
    console.log(parentId); //called over and over 

    //should GET e.g. /api/parents/1/children 
    return Restangular.one('parents', parentId).getList('children').then(function(children) { 
     console.log(JSON.stringify(children)); //never hit 
     return children; 
    }) 
} 

私は正しいAPIエンドポイントが呼び出さ取得されていますが、GetChildrenメソッド()関数は同じPARENTIDのために繰り返し呼び出され見ることができます。それはまた戻ってこないようです。私はその何かが明らかであると確信しています - 私は間違って何ですか?

この例では、Infinite loop with Angular expression bindingと関連しているようですが、例ではRestangularを使用していません。

答えて

1

なぜそれが無限に動作するのかわかりません。 AngularJsのダイジェストサイクルと関係があります。

完全にこの問題を回避するために、一つの解決策は次のようになります。

あなたは$scope.parents変数を持っています。あなたが行うことができ、その変数(あるいは少なくとも一度それが初期化されます)から:

$scope.children = {}; 

for (var parent in $scope.parents) { 
    // store parent id for easy access 
    var parentId = $scope.parents[parent].id; 
    // get the children 
    Restangular.one('parents', parentId).getList('children') 
     .then(function(children) { 
     // access the parentResource object of the returned object to 
     // get the parent id 
     $scope.children[children.parentResource.id] = children; 
    }) 
} 

この方法で、子どもたちは(親IDをキー)オブジェクトを介してアクセス可能です。あなたのhtmlでは、あなたは:

<li ng-repeat="child in children[parent.id]"></li> 

を持っていて、関数呼び出しを行うのではなく、$ scope変数にアクセスしているだけです。

関連する問題