chasingtheflow chasingtheflow - 4 months ago 21
Javascript Question

Angular Nested Controllers Access ng-repeat data

I have two controllers, one nested inside the other, both using ng-repeat to essentially list arrays of related data. I'd like to access one of the properties in the ng-repeat of the parent controller in the child controller. I'm pretty new to Angular and not sure how to get this working or if I'm approaching it the wrong way. Any guidance would be helpful.

HTML

<div class="container" ng-app="myApp">
<div class="task" ng-controller="TaskController as taskCtl" ng-repeat="task in tasks">
{{task.name}}
<ul>
<li ng-controller="AttachmentController as attachmentCtl" ng-repeat="attachment in attachments">{{attachment.name}}</li>
</ul>
</div>
</div>


JS

var app = angular.module('myApp', []);

app.controller('TaskController', ['$scope', function ($scope) {
$scope.tasks = [{name:'thing1', id: '123456'}, ... ];
}]);

app.controller('AttachmentController', ['$scope', '$http', function ($scope, $http) {
$scope.attachments = [];

$scope.init = function init() {
$http.get('/api/attachments&task_id=' + **HOW_DO_I_GET_TASK_ID_HERE** )
.then(function(response) {
$scope.attachments = response.data;
});
};

$scope.init();
}]);


I'd like to load the attachments as they relate to the tasks based on the task id for a given iteration through ng-repeat. Not sure if I'm going about this the wrong way.

Thanks

Answer

Although it would be better to use a ng-repeat with a filter on all the attachments with the given id. Since now you are calling the /api/attachments&task_id for each task iteration.

Or to send the list of attachments directly on the /api/tasks call. Therefor you could loop them instantly when looping the tasks, without the need of fetching them on each iteration.

A possible solution according to your code provided:

<div class="container" ng-app="myApp">
    <div class="task" ng-controller="TaskController as taskCtl" ng-repeat="task in tasks">
         {{task.name}}
         <ul>
             <li ng-controller="AttachmentController as attachmentCtl" ng-repeat="attachment in getAttachments(task.id)">{{attachment.name}}</li>
         </ul>
    </div>
</div>


app.controller('AttachmentController', ['$scope', '$http', function ($scope, $http) {
       $scope.getAttachments = function(id) {
          $http.get('/api/attachments&task_id=' + id)
             .then(function(response) {
                  return response.data;
          });
       };
    }]);