在socket.io事件回调中更改模型时,角度视图不会更新

时间:2015-02-15 09:40:38

标签: javascript angularjs sockets

我有一个问题,我在我的控制器中更新this.customers但它没有在视图中更新

相关功能是:

// support.js

(function(){
'use strict';

var SupportCtrl = function($state, SocketFactory){
  this.user = "Will"
  this.customers = ['will','tom']
  SocketFactory.on('queue', function(queue){
    console.log(queue)
    this.customers = queue
  })
}

angular
  .module('support',[])
  .config(['$stateProvider', function($stateProvider){
    $stateProvider
      .state('support',{
        url: '/support',
        templateUrl: 'modules/support/support.html',
        controllerAs: 'support',
        controller: 'SupportCtrl'
      })
  }])

  .controller('SupportCtrl', [
    '$state',
    'SocketFactory',
    SupportCtrl
  ])

})()

// socketService.js

(function(){
'use strict';

var SocketFactory = function($rootScope){
  var socket = io.connect();
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {  
        var args = arguments;
        console.log($rootScope)
        $rootScope.$apply(function () {
          callback.apply(socket, args);
        });
      });
    },
    emit: function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          if (callback) {
            callback.apply(socket, args);
          }
        });
      })
    }
  };
};

angular
  .module('ecomApp')
  .service('SocketFactory', [
    SocketFactory,
  ]);

})();

//的support.html

<div>
  <li ng-repeat="(roomNameKey, roomName) in support.customers">{{roomNameKey}}: {{roomName}}</li>
</div>

诊断

this.customers打印到屏幕上 0:会的 1:汤姆 但是在Socket'队列'事件中对象:

{roomName: "ikp3f"}

已成功安装console.logged但角度视图未更新

我怀疑这可能与摘要周期和$ apply()有关 - 我是否需要在SupportCtrl中调用$ apply()?

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

因为您使用

调用回调
callback.apply(socket, args);

回调中的“this”将是套接字,而不是控制器。

尝试

var SupportCtrl = function($state, SocketFactory){
  var self = this;
  self.user = "Will"
  self.customers = ['will','tom'];

  SocketFactory.on('queue', function(queue){
    console.log(queue)
    self.customers = queue
  })
}