Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I am struggling to create a model in Angular. The model is basically a parent child relationship like a ul => li relationship I have successfully bound the parent JSON array to the $scope.parents variable, and I can ng-repeat over the parent variables. However when i go to add children to the $scope.parents.children from a promised result, i get nothing in the view.

My controller code is as follows:
departmentModule.controller("departmentController", function ($scope, departmentService) { $scope.parents = []; $scope.tempArr = [];

//Load initial root/parent structure
departmentService.getParents(getSelectedEventId()).then(function (result) {
    $scope.parents = result;
    $scope.bindChildNodes()
});

//loop through  parent structure and get child nodes 1 level deep for initial load
$scope.bindChildNodes = function () {
    for (var i = 0; i < $scope.parents.length; i++) {
        var assignmentId = $scope.parents[i].ID;
        $scope.parents[i].children = [];
        departmentService.getChildren(getSelectedEventId(), assignmentId).then(function (result) {
            //i would send result to children here, but this function doesnt have access to the i var to know what parent the children belong too..
            $scope.tempArr = result;
        });
        $scope.parents[i].children = $scope.tempArr;
    }
}
});

When i assign the $scope.tempArr to the children property of its parent: $scope.parents[i].children It somehow loses its value - so a console.log of $scope.parents[0].children is an empty array. Any ideas or help with this one? Why cant I assign a JSON object to a child property of a scope variable? Simple Plunkr simulation is here Thanks so much in advance.

share|improve this question
1  
is it because you are calling bindChildNodes() before you define it (in the plunkr)? –  az7ar Dec 25 '13 at 7:49
    
OMG that seemed to fix it - ill try my real life example and see if it fixed it.. nice pickup az7ar! I assumed angular 'loaded' functions in advance of use.. Would you reconstruct the function in anyway? Thanks again.. –  user1191559 Dec 25 '13 at 8:15
    
Hey you fixed it man - i cant believe it was that simple. I must remember to order the funcs in angular first.. Would still love to know a better way to do the above if someones willing to spread the ng love....thanks! –  user1191559 Dec 25 '13 at 8:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.