dromodel
dromodel

Reputation: 10203

When is $on loaded needed in an AngularJS app?

I'm following this angular tutorial and am confused by the $on("loaded", ...) calls.

$scope.user.$on("loaded", function() {
  populatePosts();
  populatecomments();
});
...
function populatecomments() {
  $scope.comments = {};
  angular.forEach($scope.user.comments, function(comment) {
    var post = Post.find(comment.postId);
    post.$on("loaded", function() {
      $scope.comments[comment.id] = post.$child("comments").$child(comment.id);
      $scope.commentedPosts[comment.postId] = post;
    });
  });
}

Why can't we just call populatePosts() and populatComments() here? Why is a second $on("loaded", ...) needed within populatecomments() if it isn't called until loaded?

Upvotes: 1

Views: 49

Answers (2)

Jeff Hubbard
Jeff Hubbard

Reputation: 9892

In this case, it's not. You could (and should) refactor this code to use promises instead.

Upvotes: 1

Lajos Veres
Lajos Veres

Reputation: 13725

The first:

$scope.user.$on("loaded",...

will be triggered when $scope.user is loaded, the second:

post.$on("loaded",...

will be triggered for each post when the given one is loaded.

Angular(and mostly javascript) does network calls asynchronously, so if you want to postprocess their result, you have to define a callback which will be called when they are loaded.

As you see populatecomments() uses $scope.user.comments which could be inaccessible if you call populatecomments() directly, outside of the loaded event handler.

Upvotes: 1

Related Questions