【问题标题】:Angular app not updating (dirty-checking) after async call to firebase异步调用firebase后Angular应用程序未更新(脏检查)
【发布时间】:2015-02-26 22:24:43
【问题描述】:

我正在为我的博客使用单页 Angular 应用程序。加载时,控制器会调用我的 firebase 以获取所有博客文章,并将它们推送到 $scope.posts 数组中。 HTML 使用 ng-repeat 来显示每篇博文的 sn-p。但是,除非用户激活页面上的任何其他随机函数来强制执行摘要循环,否则根本不会出现 sn-ps。如何在没有用户交互的情况下进行脏检查或强制摘要循环?

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>

【问题讨论】:

标签: javascript angularjs loops firebase digest


【解决方案1】:

您需要手动触发摘要,因为在触发回调时您已超出 Angular 的范围。有几种不同的策略。使用$apply() 是一个:

        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) {

值得一提的是,如果您使用 AngularFire,这会为您处理好。 https://www.firebase.com/docs/web/libraries/angular/index.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-08
    • 2020-03-28
    • 1970-01-01
    • 2017-04-06
    • 2020-06-20
    • 2017-03-14
    • 2016-06-15
    • 1970-01-01
    相关资源
    最近更新 更多