0

I need to run a query to retrieve a list of children from each parent.

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;
    })
}

I can see the correct API endpoint is getting called, but the getChildren() function is called repeatedly for the same parentId. It also never seems to return. I'm sure its something obvious - what am I doing wrong?

Seems related to this: Infinite loop with Angular expression binding however that example doesnt use Restangular.

1 Answer 1

1

I'm not sure why it would be infinitely running. It could have something to do with AngularJs' digest cycle.

To avoid this problem entirely, one solution could be:

You have a $scope.parents variable. From that variable (or at least once it's initialized) you could do:

$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;
    })
} 

This way, the children are accessible through a object (keyed by parent id). Then in your html, you'd have:

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

and rather than making a function call, you'd just be accessing a $scope variable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.