【问题标题】:Value not updating automatically in angularJS with socket.io使用 socket.io 的 angularJS 中的值不会自动更新
【发布时间】:2014-10-14 14:08:45
【问题描述】:

以下是我的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;
          });
      });
  }     
});

【问题讨论】:

  • 如果您需要任何其他详细信息,请告诉我

标签: javascript node.js angularjs socket.io mean.io


【解决方案1】:

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

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

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

把东西分开

【讨论】:

  • 你应该写 io.connect() 而不是 io()。我希望您通过查看示例代码来自己捕捉错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
  • 2019-02-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2016-07-05
  • 1970-01-01
相关资源
最近更新 更多