0

I'm trying to display a list of products from my firebase database, but the 2 way binding is not working for me. The $scope.products gets updated and prints on the console but is not updated on the 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
    })
}])

2 Answers 2

2

Just to expand on the answer by Sajeetharan, this article has a good explanation of why calling $scope.$apply() fixes the problem.

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.

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great explanation! Thanks!
2

With firebase you can always try to apply the changes manually using $scope.$apply();

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

4 Comments

Well it works like a charm but why do I need to apply the changes?
its sometimes an issue with angularjs it does not detect the changes automatically.
Oh cool. Thanks for the quick reply! Saved me a lot of time and frustration!
@ayushgp It is not an issue with angularjs, it is actually very expected behavior. I added an answer with a link to an article explaining why this is expected in general, and why it was expected in your case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.