1

This is my code to get the data from server.

sampleApp.controller('OfferController', function ($scope, $state) {

    var offersRef = firebase.database().ref('offers');
    $scope.offers = [];

    offersRef.on('value', function(snapshot) {
      $scope.offers = snapshot.val();
      //$state.go($state.current, {}, {reload: true}); 

    });
});

Initially $scope.offers = []; is empty. It is getting filled up here. $scope.offers = snapshot.val();

But view is not updating. if i click any button or anything there on the same page, or go back and come again on same page. its getting updated.

Why is not getting updated as soon as data in available? How to fix?

2 Answers 2

12

Call $scope.$apply(); after setting the value to update the binding after setting the value.

$scope.offers = snapshot.val();
$scope.$apply();
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot for quick response. Its working fine. But what if $scope is not available? For example in Service also some place i am fetching the data like this? How to use $scope.$apply(); there??
@DeveshAgrawal you should use $scope vaiable if you are binding it to a view! , in sevices you must be using local vaiables and assigning to them
Not Actually. in service i am assigning like this. ProductService.Products = snapshot.val(); and in controller i am using same reference variable. like this:: this.ProductService = ProductService;
how do you bind that to a view without a scope variable? btw mark its as an answer if it has helped you
-1

If you use any third party code which is not in the scope of angular then it will not get updated, so you have to explicitly call $apply() method of angular. Angular monitors every time for changes to update view and it looks like snapshot.val() is not in the scope of angular so it is not getting updated on view.

You can go to this link:

https://docs.angularjs.org/api/ng/type/$rootScope.Scope

1 Comment

This does not contribute much to previous answer. You can add it as an edit to existing answer instead.

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.