0

以下是我的angularJS代码,socket.io它仅在我从视图切换时获取值,尽管我希望它会自动更新值。让我知道我在这里做错了什么 -

angular.module("app").controller("DashboardController", function($scope, SessionService) {
    $scope.user = SessionService.currentUser;

  // Code for realtime notifications
  if (SessionService.currentUser._id) {
      var socket = io('http://localhost:6868');
          socket.emit('get notifications', {user_id: SessionService.currentUser._id});
      socket.on('notification data', function(data){
          $scope.$apply(function() {
              $scope.notificationCount = data.length;
          });
      });
  }     
});
4

1 回答 1

0

我认为你不需要在这里做 $scope.$apply 。您可以在没有这个的情况下分配新值。Socket 作为 angularjs 工厂在这里看起来更好。

查看此代码以了解如何将套接字用作工厂。

https://github.com/sojharo/Simplest-Mean/blob/master/public/javascripts/MyAngularApp.js

把事情分开

于 2014-10-14T05:58:52.433 回答