简体   繁体   English

ng-init调用函数,将数据提供给ng-repeat

[英]ng-init to call function that gives data to ng-repeat

I am trying to display comments of different tasks. 我正在尝试显示不同任务的注释。 All tasks are listed on one page. 所有任务都列在一页上。 The comments should display under each tasks. 注释应显示在每个任务下。

     <div class="panel-footer">
        <div class="comment_number">Comments : {{task["comments-count"]}}  <button type="button" class="btn btn-info" data-toggle="collapse" data-target="#commentBox{{task.id}}">[+]</button></div> 
        <div ng-init="findComments(task.id)" id="commentBox{{task.id}}" class="commentShow panel-body collapse">
            <ul>
                <li ng-repeat="comment in comments">
                    <div class="avatar"><img src="{{comment['author-avatar-url']}}"/> By {{comment["author-firstname"]}}</div>
                    <div class="commentContent">{{comment.body}}</div>
                </li>
            </ul>
        </div>
  </div>

As you can see i am trying to ng-init a function which calls id of the task. 如您所见,我正在尝试ng-init一个调用任务ID的函数。 Please note that the code is already within another ng-repeat which gets all tasks looped. 请注意,该代码已经在另一个ng-repeat中,该代码使所有任务循环执行。

<li class="list-group-item" ng-repeat="task in myTaskfromList">
   ...... code above is actually here after task details..
</li>

Problem is the code only displays the first looped tasks comment lists and the content of comments. 问题是代码仅显示第一个循环的任务注释列表和注释内容。 It does not display the other task comments but overwrites the second task comment place with first task comment. 它不显示其他任务注释,而是用第一个任务注释覆盖第二个任务注释位置。

Now i tried to do this 现在我试图做到这一点

<li ng-init="findComments(task.id)" class="list-group-item" ng-repeat="task in myTaskfromList">

</li>

This doesn't show anything.. 这什么也没显示。

Here is my controller 这是我的控制器

//get comments from task
$scope.findComments = function(taskId) {
  $http.get("http://abounde.com/portal/api/task/"+taskId).then(function(response) {
    $scope.comments = response.data.comments;
  });
}

Could you kindly advice me efficient solution? 您能为我提供有效的解决方案吗?

So, you have nested ng-repeat blocks and each block is making its own xhr requests? 那么,您有嵌套的ng-repeat块,并且每个块都在发出自己的xhr请求? This sounds particularly inefficient. 这听起来效率特别低。 Assuming that you have control over the rest API that you are working with, things will be significantly faster and easier to manage if you augment the http://abounde.com/portal/api/task/ to take a list of task ids and then iterate through them all at once. 假设您可以控制要使用的其余API,那么如果您增加http://abounde.com/portal/api/task/来获取任务ID和然后一次遍历它们。

You really shouldn't be using ng-init like this, or generally at all. 您真的不应该这样使用ng-init ,或者根本不应该使用。 See the warning in the documentation . 请参阅文档中的警告。 Fetching data when a page loads should be done in the controller, no the template. 页面加载时获取数据应在控制器中完成,而无需模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM