livi1717 livi1717 - 2 months ago 9
Javascript Question

$scope variable in HTML disappearing on refresh

I have a scope variable that appears properly as it should when coming from somewhere else on the site. However, if the html page where the $scope variable is called from is refreshed, the variable value disappears.

My controller looks like this:

angular.module('testApp')
.controller('TestShowCtrl', function($scope, Ref, $routeParams) {
//Get ID out of current URL
var currentId = $routeParams.id;

var ref = new Firebase(Ref + 'events').child(currentId);

ref.on('value', function(snapshot) {
var data = snapshot.val();
console.log('data.title: ' + data.title);
$scope.title = data.title;

});
});


My HTML looks like this:

<h3 id="test">Title: {{title}}</h3>


Strangely, while the HTML does not display the variable, it still appears in the console after refresh.

Answer

Synchronizing data from Firebase is an asynchronous operation. By the time the data comes back from Firebase and you bind it to the scope, AngularJS is not expecting changes anymore. So it doesn't immediately update the UI, but instead does so on the next "refresh cycle".

To trigger an immediate update, call $timeout() or $apply():

angular.module('testApp')
 .controller('TestShowCtrl', function($scope, Ref, $routeParams) {
    //Get ID out of current URL
    var currentId = $routeParams.id;

    var ref = new Firebase(Ref + 'events').child(currentId);

    ref.on('value', function(snapshot) { $timeout(function() {
        var data = snapshot.val();
        console.log('data.title: ' + data.title);
        $scope.title = data.title;
    })});
});
Comments