我正在尝试显示我的 firebase 数据库中的产品列表,但 2 路绑定(bind)对我不起作用。 $scope.products
已更新并在控制台上打印,但未在 UI 上更新。
app.controller("productManagerController", ["$scope", function ($scope) {
$scope.products = [];
db.ref("products").once('value').then(function (snapshot) {
const values = snapshot.val()
for (key in values) {
values[key].id = key;
$scope.products.push(values[key])
}
console.log($scope.products) // Logs the values that have been taken from firebase
// But doesn't update on the UI
})
}])
最佳答案
只是为了扩展 Sajeetharan 的答案,this article有一个很好的解释为什么打电话 $scope.$apply()
解决问题。
When Do You Call $apply() Manually?
If AngularJS usually wraps our code in $apply() and starts a $digest cycle, then when do you need to do call $apply() manually? Actually, AngularJS makes one thing pretty clear. It will account for only those model changes which are done inside AngularJS’ context (i.e. the code that changes models is wrapped inside $apply()). Angular’s built-in directives already do this so that any model changes you make are reflected in the view. However, if you change any model outside of the Angular context, then you need to inform Angular of the changes by calling $apply() manually. It’s like telling Angular that you are changing some models and it should fire the watchers so that your changes propagate properly.
本质上,db.ref(..)...
调用未包含在 $apply
中由于它不在 AngularJS 的上下文中,因此,您必须自己调用它。
关于javascript - Angular 中的 2 路绑定(bind)不适用于 firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48549576/