2017-02-15 66 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变量。