0

I'm trying to refresh the controller of my angular app to receiving objects from socket.io. Everything works fine except that the view don't show when I add a new object to the variable with the push function. Here's my code.

Controller.js

app.controller('controller', function(){
var vm = this;
var socket = io.connect('http://localhost:3000');
//The variable that bends
vm.messages = [];

socket.on("addMsg", function(obj){
    vm.messages.push({user: obj.user, content: obj.content, color:obj.col});
});


});

view.jade

    ...
 body(ng-controller = "controller as con")
.messages
    p Messages:
    p(ng-repeat="array in con.messages") content: {{array.content}} , color: {{array.color}}

Whats wrong with my code?, the purpose is to show all content in p tag using ng-repeat.

Cesar Jr Rodriguez
  • 1,691
  • 4
  • 22
  • 35
  • 1
    it's likely you need an $apply around vm.messages.push as it's within the socket callback – aw04 Jan 15 '16 at 19:55

2 Answers2

2

This tiny angular factory socket service from html5rocks article angular-websocket wraps socket.io in angular scope. It does the auto $rootScope.$apply()

app.factory('socket', function ($rootScope) {
  var socket = io.connect();
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {  
        var args = arguments;
        $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);
          }
        });
      })
    }
  };
});
Henry Zou
  • 1,809
  • 1
  • 14
  • 19
0

I had the exact same problem when I was trying to update an angular scope variable inside of the socket.on callback. Just as @aw04 mentioned in his comment, the fix was to make a simple call to $scope.$apply()

BoJoe22
  • 85
  • 2
  • 9