javascript - Angular 中的 2 路绑定(bind)不适用于 firebase

标签 javascript angularjs firebase firebase-realtime-database

我正在尝试显示我的 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/

相关文章:

javascript - 打破谷歌图表图例标签

javascript - 如何从 angular2 项目访问 "$wakanda"服务以检索数据?

javascript - 从另一个嵌套 Controller 调用函数

javascript - 错误: Property 'getChildren' does not exist on type 'DataSnapshot'

java - Firebase .indexOn 未按预期工作

javascript - 创建函数数组的实际原因?

javascript - 在字段中输入文本时,关联的标签消失: How to find guilty JavaScript

javascript - html/css/jquery 点击元素和所有触发事件

javascript - 使用 Angularjs 是否有更新数组中对象的最佳实践?

firebase - 是否可以在一个项目中创建多个 Firebase 实时数据库实例(>20)