2017-02-15 82 views
0

我需要運行一個查詢來檢索每個父級的子級列表。Restangular嵌套子查詢無限循環

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變量。