我正在通过Firebase处理一些数据,由于某些原因,当服务器上的值发生变化时,我的控制台中的范围会更新,但角度视图不会更新。
我尝试过一些不同的方法,包括在$timeout
& $apply
,但仍无法解决。我曾经多次使用角度,我以前从未遇到过这种行为。应用程序中只有一个控制器。
JS
app.controller('someCtrl', function($scope, $timeout){
$scope.publishedItems =[];
var fbRef = firebase.database().ref('stories/' + storyId + "/correspondents").orderByChild('published').equalTo(true);
fbRef.on('value', function(snapshot) {
//update scope
$scope.publishedItems = snapshot.val();
console.log($scope.publishedItems)// this logs the correct data, however the markup is not changing
});
HTML 的
<div ng-controller="someCtrl">
<div ng-repeat="item in publishedItems">
{{item}}
</div>
</doc>
解决
所以在经过一些调试之后,事实证明我在Angular应用程序之外运行了一个函数,它正在向dom添加一些标记,这会干扰Angulars摘要周期。
现在按预期工作
答案 0 :(得分:2)
假设snapshot.val()返回一些内容,你需要触发一个摘要周期来确定更改,因为firebase回调是在angular之外执行的
fbRef.on('value', function(snapshot) {
$scope.$apply(function(){
$scope.publishedItems = snapshot.val();
})
})
答案 1 :(得分:0)
您可以尝试以下代码
var app = angular.module('myApp', []);
app.controller('someCtrl', function ($scope, $timeout) {
$scope.publishedItems = [];
$scope.$watchCollection('publishedItems', function(newCol, oldCol, scope) {
console.log(newCol, oldCol, scope);
});
var fbRef = firebase.database().ref('stories/' + storyId + "/correspondents").orderByChild('published').equalTo(true);
fbRef.on('value', function (snapshot) {
var pubItems = snapshot.val();
//update scope
$scope.publishedItems = pubItems;
console.log($scope.publishedItems)// this logs the correct data, however the markup is not changing
});
});
答案 2 :(得分:0)
好像你需要更新绑定,所以你需要使用$scope.$apply()
app.controller('someCtrl', function($scope, $timeout){
$scope.publishedItems =[];
var fbRef = firebase.database().ref('stories/' + storyId + "/correspondents").orderByChild('published').equalTo(true);
fbRef.on('value', function(snapshot) {
//update scope
$scope.publishedItems = snapshot.val();
console.log($scope.publishedItems)// this logs the correct data, however the markup is not changing
});
$scope.$apply();
});