2017-07-25 95 views
0

我确定这是一个非常普遍的问题,但由于某种原因,我无法找到可行的解决方案。

我有火力地堡实时数据库和角1.一个非常简单的设置我有这个指令在我的HTML

<div id="usersListWrapper" ng-controller="UsersListController" ng-init="loadUsersList()"> 

然后我loadUsersList()方法里面,我做出火力地堡调用数据库获取数据

$rootScope.users = []; 

var usersRef = firebase.database().ref('/users'); 
usersRef.on('value', function(snapshot) { 
    console.log("loaded users list"); 
    var users = snapshot.val(); 
    updateUsersTable(users); 
}); 

后来终于,里面updateUsersTable(users),更新我的$rootScope.users变量

var updateUsersTable = function(users) { 
    $.each(users, function(key, value) { 
     var user = { 
      username: key, 
      ... 
     } 

     $rootScope.users.push(user); 
    } 
} 

然而,即使正确$rootScope.users变量更新(我验证了使用Chrome的devtools),html的不更新:提前/

道歉,如果这是一个重复的问题。帮助将不胜感激。

+2

这听起来像你需要运行一个摘要循环。 $ scope。$ apply(function(){$ rootScope.users.push(user);}); – LT56

+0

@ LT56从我读的内容来看,手动调用'$ apply'是不好的。但是,我也尝试过,并且每次向列表添加内容时都会引发问题。我一直得到这个:'错误:$应用已经在进行中' – Bazinga

+0

我会把范围。$应用于事件监听器b/c AngularJS不知道事件何时被触发,因为它不管理它。即:usersRef.on('value',scope。$ apply(function(){<您的代码在这里}}); – flyer

回答

0

$ rootScope不适合您存储您的用户对象。一般来说,修改$ rootScope应该被认为是您在没有其他选项时执行的操作。

你应该做的是创建一个userService并注入它,无论你需要访问用户数据。

同样的建议通常也适用于使用ng-init。我猜你刚刚开始使用Angularjs。我强烈推荐您熟悉John Papa的Angularjs风格指南:https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md。这有点过时,因为它没有涵盖任何组件,但遵循样式指南使组件迁移变得非常容易。

0

正如我在评论中提到上面我会把范围。在事件侦听器B/C AngularJS时会触发事件,因为它不是管理,它不知道$适用。即:

usersRef.on('value', scope.$apply(function() { 
    console.log("loaded users list"); 
    var users = snapshot.val(); 
    updateUsersTable(users); 
})); 

或者你可以看看$ evalAsync。从AngularJS文档:

$evalAsync([expression], [locals]); Executes the expression on the current scope at a later point in time.

The $evalAsync makes no guarantees as to when the expression will be executed, only that:

it will execute after the function that scheduled the evaluation (preferably before DOM rendering). at least one $digest cycle will be performed after expression execution.