AngularJS binding only updating after change

Hi I have created a factory to get the current amount of users online from my Firebase database.

When I first load the page it works great and displays all the current users but then if I go to another page and come back it will display as 0 until a new user connects or disconnects or if I refresh.

I followed this guide: http://www.ng-newsletter.com/advent2013/#!/day/9

App.js

angular.module('myApp', ['ngRoute', 'firebase', 'ui.bootstrap'])
.factory('PresenceService', ['$rootScope',
  function($rootScope) {
    var onlineUsers = 0;

    // Create our references
    var listRef = new Firebase('https://my-db.firebaseio.com/presence/');

    // This creates a unique reference for each user
    var onlineUserRef = listRef.push(); 
    var presenceRef = new Firebase('https://my-db.firebaseio.com/.info/connected');

    // Add ourselves to presence list when online.
    presenceRef.on('value', function(snap) {
      if (snap.val()) {
        onlineUserRef.set(true);
        // Remove ourselves when we disconnect.
        onlineUserRef.onDisconnect().remove();
      }
    });

    // Get the user count and notify the application
    listRef.on('value', function(snap) {
      onlineUsers = snap.numChildren();
      $rootScope.$broadcast('onOnlineUser');
    });

    var getOnlineUserCount = function() {
      return onlineUsers;
    }

    return {
      getOnlineUserCount: getOnlineUserCount
    }
  }
]);

mainController.js

angular.module('myApp')
.controller('mainController', function($scope, authService, PresenceService, $http, $routeParams, $firebaseObject, $firebaseAuth, $location) {

  $scope.totalViewers = 0;

  $scope.$on('onOnlineUser', function() {
    $scope.$apply(function() {
      $scope.totalViewers = PresenceService.getOnlineUserCount();
    });
  });

  // login section and auth
  var ref = new Firebase("https://my-db.firebaseio.com");
  $scope.authObj = $firebaseAuth(ref);
  var authData = $scope.authObj.$getAuth();
  if (authData) {
    console.log("Logged in as:", authData.uid);
    $location.path( "/user/"+authData.uid );
  } else {
    console.log("Logged out");
    $location.path( "/" );
  }

  // user ref
  var userRef = new Firebase("https://my-db.firebaseio.com/users/"+ authData.uid);
  var syncObject = $firebaseObject(userRef);
  syncObject.$bindTo($scope, "data");

});

main.html

{{totalViewers}}

Inside your controller, change yr first line as below.

 //$scope.totalViewers = 0;
$scope.totalViewers = PresenceService.getOnlineUserCount();

Because each time you leave the page, its controller gets flushed and next time its getting value "zero". So, correctly you should read $scope.totalViewers from your service.