简体   繁体   中英

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. Please note that the code is already within another ng-repeat which gets all tasks looped.

<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? 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.

You really shouldn't be using ng-init like this, or generally at all. See the warning in the documentation . Fetching data when a page loads should be done in the controller, no the template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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