简体   繁体   English

2角度绑定的角度不适用于firebase

[英]2 Way binding in angular not working with firebase

I'm trying to display a list of products from my firebase database, but the 2 way binding is not working for me. 我正在尝试显示我的Firebase数据库中的产品列表,但是2种方式的绑定对我不起作用。 The $scope.products gets updated and prints on the console but is not updated on the UI. $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
    })
}])

With firebase you can always try to apply the changes manually using $scope.$apply(); 使用firebase时,您始终可以尝试使用$scope.$apply();手动应用更改$scope.$apply();

 $scope.products.push(values[key])
 $scope.$apply();

Just to expand on the answer by Sajeetharan, this article has a good explanation of why calling $scope.$apply() fixes the problem. 只是为了扩展Sajeetharan的答案, 本文很好地解释了为什么调用$scope.$apply()可解决此问题。

When Do You Call $apply() Manually? 您何时手动调用$ apply()?

If AngularJS usually wraps our code in $apply() and starts a $digest cycle, then when do you need to do call $apply() manually? 如果AngularJS通常将我们的代码包装在$ apply()中并开始$ digest循环,那么您何时需要手动调用$ apply()? Actually, AngularJS makes one thing pretty clear. 实际上,AngularJS使一件事很清楚。 It will account for only those model changes which are done inside AngularJS' context (ie the code that changes models is wrapped inside $apply()). 它只会考虑在AngularJS的上下文中完成的那些模型更改(即,更改模型的代码包装在$ apply()中)。 Angular's built-in directives already do this so that any model changes you make are reflected in the view. Angular的内置指令已经做到了,这样您所做的任何模型更改都会反映在视图中。 However, if you change any model outside of the Angular context, then you need to inform Angular of the changes by calling $apply() manually. 但是,如果您在Angular上下文之外更改任何模型,则需要通过手动调用$ apply()来通知Angular更改。 It's like telling Angular that you are changing some models and it should fire the watchers so that your changes propagate properly. 这就像告诉Angular您正在更改某些模型,并且应该触发观察程序,以便您的更改正确传播。

So essentially, the db.ref(..)... call is not wrapped in an $apply since it is not within AngularJS' context, therefore, you must call it yourself. 因此,从本质db.ref(..)...db.ref(..)...调用未包装在$apply因为它不在AngularJS的上下文中,因此,您必须自己调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM