4

I am using a single page angular app for my blog. On load, the controller makes a call to my firebase for all blog posts and pushes them into a $scope.posts array. The HTML employs ng-repeat to display a snippet of each blog post. However, no snippets appear at all unless the user activates any other random function on the page to force the digest loop. How can I make it dirty check or force the digest loop without user interaction?

angular.module('evancodes.main', [])
.controller('MainController', function(Main, $http, $scope) {
    $scope.posts = [];
    $scope.getAllPosts = function() {
        var ref = new Firebase("https://MYFIREBASENAME.firebaseio.com/");
        ref.on("value", function(snapshot) {
            var posts = snapshot.val();
            for (var post in posts) {
                $scope.posts.push(posts[post]);
            }
        }, function (errorObject) {
          console.log("The read failed: " + errorObject.code);
        });
    }
    $scope.getAllPosts();
})

HTML:

<div class="snippets col-md-9 col-md-offset-1" ng-repeat="post in posts | limitTo: 5">
  <a href="#/posts/{{post.url}}">
      <div class="snippetTitle"> 
          {{post.title}}
      </div>
      <div class="snippetBody" ng-bind-html="post.content | limitTo: 650"></div>
  </a>
</div>
Antiga
  • 2,264
  • 1
  • 20
  • 28
evancodes
  • 73
  • 4
  • possible duplicate of [How come Angular doesn't update with scope here?](http://stackoverflow.com/questions/21922470/how-come-angular-doesnt-update-with-scope-here) – Kato Jan 02 '15 at 16:59

1 Answers1

4

You'll need to manually fire the digest since you are outside of Angular's scope by the time the callback is fired. There are a couple different strategies. Using $apply() is one:

        ref.on("value", function(snapshot) {
            var posts = snapshot.val();
            for (var post in posts) {
                $scope.posts.push(posts[post]);
            }
            $scope.$apply(); // RUN DIGEST HERE
        }, function (errorObject) {

It's worth mentioning that if you use AngularFire, this is taken care of for you. https://www.firebase.com/docs/web/libraries/angular/index.html

Antiga
  • 2,264
  • 1
  • 20
  • 28