Angular view does not update when model changes in socket.io event callback

I have a problem that I am updating this.customers in my controller, but it is not updating in the view

Relevant Features:

//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>

Diagnostics

this.customers prints on screen 0: will be 1: Tom But in the Socket event "queue" object:

{roomName: "ikp3f"}

console.logged successfully, but angular view not updating

I suspect this might be related to the digest loop and $ apply () - do I need to call $ apply () in my SupportCtrl?

thanks for the help

+4
source share
1 answer

Since you are calling a callback with

callback.apply(socket, args);

"this" , .

Try

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
  })
}
+2

All Articles