Ionic Creator导出项目无.ts文件,ng-repeat数据无法自动显示问题
解决AngularJS ng-repeat在Firebase异步回调中不渲染的问题
你遇到的核心问题是AngularJS的脏检查机制没检测到$scope的更新——Firebase的on("value")回调是在Angular的消化周期(digest cycle)之外执行的,所以即使你更新了$scope.groceries,视图也不会自动刷新;而点击侧边菜单会触发一次消化周期,这时候Angular才会发现数据变化并渲染页面。
快速修复方案
有两种简单的方式可以解决这个问题:
方案1:手动触发脏检查
在给$scope.groceries赋值后,调用$scope.$apply()强制Angular执行消化周期:
firebase.database().ref("table").orderByChild("user").equalTo("userid").on("value", function(snapshot) { var credit = 0; var groceryHistory = []; snapshot.forEach(function(childSnapshot) { var childData = childSnapshot.val(); if(childData.type == 1 && childData.used == 1) { groceryHistory.push(childData); } }); console.log(groceryHistory); $scope.groceries = groceryHistory; // 手动触发Angular的脏检查,更新视图 $scope.$apply(); });
方案2:用$timeout包裹赋值操作
Angular的$timeout服务会自动触发消化周期,记得先在控制器中注入$timeout依赖:
// 控制器定义时注入$timeout .controller('groceryCtrl', ['$scope', '$timeout', function($scope, $timeout) { firebase.database().ref("table").orderByChild("user").equalTo("userid").on("value", function(snapshot) { var credit = 0; var groceryHistory = []; snapshot.forEach(function(childSnapshot) { var childData = childSnapshot.val(); if(childData.type == 1 && childData.used == 1) { groceryHistory.push(childData); } }); console.log(groceryHistory); // 用$timeout包裹赋值,让Angular自动处理消化周期 $timeout(function() { $scope.groceries = groceryHistory; }); }); }]);
额外排查建议
- 先确认控制器和模板的关联是否正确:比如在路由配置或视图标签中指定了
controller="groceryCtrl" - 可以在模板中添加调试代码
<pre>{{ groceries | json }}</pre>,直接查看$scope中的数据是否正确赋值,排除模板绑定的问题
内容的提问来源于stack exchange,提问作者Ophitect
相关产品推荐
相关产品推荐

