Firebase snapshot.val()未绑定到$ scope

时间:2016-07-11 15:03:49

标签: angularjs firebase firebase-realtime-database angularfire

我正在使用FireBase并尝试进行一些查询,结果是登录但在HTML $scope中不可见。

var shopRef = firebaseDataService.intro;

$scope.shops = [];

var taskRef = shopRef.orderByChild("cat").equalTo("Accomodation");


taskRef.on("value", function(snapshot) {
    var snapData = snapshot.val();
    console.log(snapData);
    $scope.shops.push(snapData);

});

当我使用$scope.$apply()时,我设法将数据更新到商店,但它仍未将任何内容传递给我的指令。

    <search-card shops="shops">   </search-card>
    <p> Shops are {{shops}}</p>

我用$ firebaseArray

以某种方式工作了
  $scope.shops = $firebaseArray(taskRef);

但是我仍然想知道我做错了什么以及为什么它不能处理快照。

1 个答案:

答案 0 :(得分:5)

来自angularfire docs

// read data from the database into a local scope variable
ref.on("value", function(snapshot) {

    // Since this event will occur outside Angular's $apply scope, we need to notify Angular
    // each time there is an update. This can be done using $scope.$apply or $timeout. We
    // prefer to use $timeout as it a) does not throw errors and b) ensures all levels of the
    // scope hierarchy are refreshed (necessary for some directives to see the changes)
    $timeout(function() {
      $scope.data = snapshot.val();
    });
});

似乎使用$scope.apply()不会刷新整个层次结构(因此也不会刷新指令)。请尝试按照规定使用$timeout

话虽如此,我认为你应该选择$firebaseArray()选项,因为这是最“有棱角”的解决方案