首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角嵌套控制器访问ng重复数据

角嵌套控制器访问ng重复数据
EN

Stack Overflow用户
提问于 2016-07-20 21:32:49
回答 2查看 483关注 0票数 0

我有两个控制器,一个嵌套在另一个控制器中,它们都使用ng重复来列出相关数据的数组。我想访问子控制器中父控制器的ng重复中的一个属性。我对棱角很陌生,不知道该怎么做,或者我是不是走错了路。任何指导都会有帮助。

代码语言:javascript
复制
<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

代码语言:javascript
复制
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。不知道我是不是走错路了。

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-07-20 21:48:13

不过,最好在带有给定id的所有附件上使用ng-重复和筛选器。从现在开始,您将为每个任务迭代调用/api/attachments&task_id

或者直接在/api/tasks调用上发送附件列表。因此,您可以在循环任务时立即循环它们,而无需在每次迭代中获取它们。

根据您的代码提供了一个可能的解决方案:

代码语言:javascript
复制
<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
EN

Stack Overflow用户

发布于 2016-07-20 21:38:56

子控制器中的类似内容应该可以工作: HTML:

代码语言:javascript
复制
<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调用的结果“返回”此函数才能正常工作。

代码语言:javascript
复制
$scope.fetchAttachments = function (task) {
    // call ajax 
    // return the result of ajax
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38491214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档