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.

1
  • 1
    it's likely you need an $apply around vm.messages.push as it's within the socket callback Commented Jan 15, 2016 at 19:55

2 Answers 2

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);
          }
        });
      })
    }
  };
});
Sign up to request clarification or add additional context in comments.

Comments

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.