1

I'm trying to use PrivatePub within my Angular app. I've a chat and messages are managed by AngularJS, my API behind is running with Rails, in my controller I use the helper to Publish to the channel, my problem is on the client side with the Subscribe. Here is what I try to do:

chat.controller("MessageController", ['$scope','Message','Project', function($scope,Message,Project) {
    //Fetch messages
    Message.query(function(data) {
        $scope.messages = data;
    });

    PrivatePub.subscribe(Project.channel, function(data, channel) {
        $scope.messages.push(data.message);
    });
}]);

I tried to use $apply and $watch around my PrivatePub subscribe, no way to update my scope. My PrivatePub function should be outside Angular but the data it receives should be added to the $scope.I don't what other solution I could try.

  • 1
    `it didn't work` isn't much of explanation. How did you try using `$apply` and what happened? errors thrown? – charlietfl Sep 13 '14 at 12:24
  • First I got `Error: $digest already in progress`, I found some answers such as this one `if(!$scope.$$phase) { //$apply }` which is not recommended apparently, when I use it my code is not executed at all. When I used $watch my code is executed but the scope is not updated. – Thomas Quiroga Sep 13 '14 at 13:24
  • try using `$timeout`, will wait for digest to be completed – charlietfl Sep 13 '14 at 13:26
  • I just tried with $timeout like [here](https://github.com/angular-ui/ui-codemirror/issues/30#issuecomment-50852379) The scope is not immediately updated, I receive the data instantly in my console, but the view is not updated until I trigger some events on my UI. It's like Angular is not aware that the scope get a new value. – Thomas Quiroga Sep 13 '14 at 13:40

1 Answers1

2

Ok I found the problem, I was not using $apply correctly, I was basically doing:

$timeout(function () {
  $scope.$apply(function($scope) {
    PrivatePub.subscribe("/mychannel", function(data, channel) {
      $scope.addMessage(data.chat_message);
    });
  });
}, 0);

Instead of:

$timeout(function () {
   PrivatePub.subscribe("/mychannel", function(data, channel) {
     $scope.$apply(function($scope) {
       $scope.addMessage(data.chat_message);
     });
   });
}, 0);

The changes I want to notify to Angular is not the function itself but what happened inside. Just a bad use.