javascript – 在对firebase进行异步调用之后,Angular应用程序不会更新(脏检查)

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

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>

解决方法:

您需要手动触发摘要,因为在回调被触发时您不在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

上一篇:对密码进行加密,并转换为十六进制


下一篇:谷歌身份认证 Python实现