我有两个控制器,一个嵌套在另一个控制器中,它们都使用ng重复来列出相关数据的数组。我想访问子控制器中父控制器的ng重复中的一个属性。我对棱角很陌生,不知道该怎么做,或者我是不是走错了路。任何指导都会有帮助。
<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();
}]);我想通过ng-重复加载附件,因为它们与任务有关,基于给定迭代的任务id。不知道我是不是走错路了。
谢谢
发布于 2016-07-20 21:48:13
不过,最好在带有给定id的所有附件上使用ng-重复和筛选器。从现在开始,您将为每个任务迭代调用/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;
});
};
}]);发布于 2016-07-20 21:38:56
子控制器中的类似内容应该可以工作: 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子控制器:这个fetchAttachments将在父ngRepeat的每一次迭代中调用。您必须将Ajax调用的结果“返回”此函数才能正常工作。
$scope.fetchAttachments = function (task) {
// call ajax
// return the result of ajax
}https://stackoverflow.com/questions/38491214
复制相似问题