WebGavDev
WebGavDev

Reputation: 33

Firebase Database Function Can't Modify a $scope variable in angularjs

I have the following code:

angular.module("MyApp", ['textAngular'])
.controller("demoController", function demoController($scope) {
    $scope.content = null;
    firebase.database().ref('pages/home').on('value', function(snapshot) { $scope.content = snapshot.val(); });
    console.log($scope.content);
});

As you can see, all I am trying to do is change a variable in the scope of my controller within a function that accesses the firebase database, in order to store the contents of a certain entry. When attempting this however, the variable simply does not change. I have tried the same thing using 'window.content', as well as trying to use 'var content;' to no avail. Is there any way to allow a variable to be globally accessed from within a function?

edit - When I run the firebase.databse().ref fucntion and use alert(snapshot.val()); it works and the information is displayed in the alert.

Upvotes: 1

Views: 540

Answers (4)

WebGavDev
WebGavDev

Reputation: 33

None of those methods worked, however I ended up solving the problem by doing this:

var app = angular.module("textAngularDemo", ['textAngular'])
app.controller("demoController", function demoController($scope) {
    firebase.database().ref('pages/home').on('value', function(snapshot) {     
        test($scope, snapshot.val());
    });
    $scope.detectChange = function(){
        setTimeout(function(){
            if ($scope.content)
            {
                console.log ($scope.content);
                }
            }
            else
            {
                $scope.detectChange();
            }
        }, 1);
    }
    function test(scope, variable){
        scope.content = variable;
        $scope.$apply();
    }
    setTimeout(function(){ $scope.detectChange() }, 1);
});

I believe this is acts in the same way as a promise, however I had no knowledge of how to implement them at the time. Call this a 'pseudo promise' if you will.

Upvotes: 1

Silent Coder
Silent Coder

Reputation: 1

Try this

firebase.database().ref('pages/home').on('value', function(snapshot) {     scope.$apply(function(){$scope.content = snapshot.val().content });});

Upvotes: 0

CD..
CD..

Reputation: 74126

Use $apply():

$apply() is used to execute an expression in angular from outside of the angular framework (For example from browser DOM events, setTimeout, XHR or third party libraries).

For example:

firebase.database()
  .ref('pages/home')
  .on('value', function(snapshot) {     
    $scope.$apply(function(){
      $scope.content = snapshot.val();
    });
});

Upvotes: 4

The Dark Knight
The Dark Knight

Reputation: 727

Firebase is asynchronous, (ie The rest of the code will run without waiting for the firebase function to run. Put the console.log inside the on function, you will see that the scope variable has in fact changed.

Upvotes: 1

Related Questions