【发布时间】:2016-07-21 06:24:42
【问题描述】:
我有两个控制器,一个嵌套在另一个内部,都使用 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 进行的给定迭代。不知道我是不是走错了路。
谢谢
【问题讨论】:
-
既然你用
$scope这种东西:ng-controller="TaskController as taskCtl"是不必要的,应该只有ng-controller="TaskController"。 -
@developer033 谢谢......我不明白为什么/如何使用 $scope 使这变得不必要。你能详细说明一下,或者这两种方法是什么?
-
@developer033 谢谢,这使整个问题更加清晰。我将两者结合起来,看到它以两种方式完成,但不理解差异。
标签: javascript angularjs