Vadym Kaptan
Vadym Kaptan

Reputation: 88

Angular Binding Bug

i have factory 'Chat' that connect to my nodejs server by socket.io and send message to server.

.factory('Messages', function($ionicScrollDelegate){
    var messages = [];
    return {
      getMessages : function(){
        return messages;
      },
      setMessage : function(msg){
        messages.push(msg);
      }
    }
  })    
.factory('Chat', function(Socket, Messages){
    Socket.on('onChat', function(data){
       if (data.from !== username){
          Messages.setMessage({username : data.from, message : data.msg});
       }
    });
    return : {
       sendMessage: function(msg){
          Messages.setMessage({
             username: username,
             message: msg
          });
          Socket.request(route, {
             rid: 'AA',
             content: msg,
             from: username,
             target: '*'
          }, function() {
          });
    }

and my controller whitch check messages arr from factory.

.controller('livePageCtrl', function($scope, Messages, Chat){
   $scope.data = {};
   $scope.data.message = "";
   $scope.messages = Messages.getMessages();
   $scope.sendMessage = function(msg){
      Chat.sendMessage(msg);
      $scope.data.message = "";
   };
});

and my view form

<div class="chat">
   <div class="row" ng-repeat="message in messages track by $index">
      <div class="col col-100"">
         {{message.message}}
      </div>
    </div>
 </div>
 <input ng-model="data.message" type="text" placeholder="Chat to Room">
 <button type="submit" ng-click="sendMessage(data.message)"></button>

When i typing message and press button to send my arr messages updated and i can see message in the DOM, but if i getting new message from server my messages arr is updated but DOM is not updated. Only after i start typping new message DOM updated and I can see the incoming message. What i do wrong? Why my DOM don't update after new message from server? Thanks to all! And sorry for my english)

Upvotes: 0

Views: 66

Answers (1)

Miles P
Miles P

Reputation: 710

The issue here is the $digest cycle is not being run, most likely because Angular does not know when new items arrive from the socket. Angular normally runs the $digest cycle automatically such as when ng-click is fired or an $http call resolves. However in this case you'll need to manually invoke this process.

You can try:

Socket.on('onChat', function(data){
   if (data.from !== username){
      $timeout(function(){
          Messages.setMessage({username : data.from, message : data.msg});
      });          
   }
});

Don't forget to import $timeout into your Chat factory.

Upvotes: 1

Related Questions