我有两个控制器,一个嵌套在另一个控制器内,都使用ng-repeat来基本列出相关数据的数组。我想访问子控制器中父控制器的ng-repeat中的一个属性。我是Angular的新手,不知道如何让这个工作或者我以错误的方式接近它。任何指导都会有所帮助。
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();
}]);
我想加载附件,因为它们与基于任务ID的任务相关,通过ng-repeat进行给定的迭代。我不确定我是否会以错误的方式解决这个问题。
由于
答案 0 :(得分:1)
尽管在具有给定id的所有附件上使用带有过滤器的ng-repeat会更好。从现在开始,您为每个任务迭代调用/api/attachments&task_id
。
或直接在/api/tasks
电话上发送附件列表。因此,您可以在循环任务时立即循环它们,而无需在每次迭代时获取它们。
根据您提供的代码提供的可能解决方案:
<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;
});
};
}]);
答案 1 :(得分:0)
来自子控制器的这样的东西应该工作: HTML:
<div class="container" ng-app="myApp">
<div class="task" ng-controller="TaskController" ng-repeat="task in tasks">
{{task.name}}
<ul>
<li ng-controller="AttachmentController" ng-repeat="attachment in fetchAttachments(task)">{{attachment.name}}</li>
</ul>
</div>
</div>
JS 儿童控制器: 将为父ngRepeat的每次迭代调用此fetchAttachments。你将不得不返回&#34; Ajax调用此函数以使其工作的结果。
$scope.fetchAttachments = function (task) {
// call ajax
// return the result of ajax
}