【问题标题】:AngularJS binding only updating after changeAngularJS 绑定仅在更改后更新
【发布时间】:2015-03-14 19:25:45
【问题描述】:

您好,我创建了一个工厂来从我的 Firebase 数据库中获取当前在线用户数量。

当我第一次加载页面时,它运行良好并显示所有当前用户,但如果我转到另一个页面并返回,它将显示为 0,直到新用户连接或断开连接或刷新。

我遵循了本指南: 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
    }
  }
]);

ma​​inController.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");

});

ma​​in.html

{{totalViewers}}

【问题讨论】:

    标签: javascript angularjs firebase


    【解决方案1】:

    在您的控制器中,将您的第一行更改如下。

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

    因为每次您离开页面时,它的控制器都会被刷新,并且下次它的值“零”。因此,您应该正确地从您的服务中读取 $scope.totalViewers。

    【讨论】:

      猜你喜欢
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-18
      • 2013-06-09
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多