1

我正在尝试在我的 Angular 应用程序中使用PrivatePub 。我有一个聊天,消息由 AngularJS 管理,我背后的 API 使用 Rails 运行,在我的控制器中,我使用助手发布到频道,我的问题出在客户端的订阅。这是我尝试做的事情:

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);
    });
}]);

我试图在我的 PrivatePub 订阅中使用 $apply 和 $watch,但无法更新我的范围。我的 PrivatePub 函数应该在 Angular 之外,但它接收到的数据应该添加到 $scope。我不知道我可以尝试什么其他解决方案。

4

1 回答 1

2

好的,我发现了问题,我没有$apply正确使用,我基本上是在做:

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

代替:

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

我想通知 Angular 的变化不是函数本身,而是内部发生的事情。只是不好用。

于 2014-09-13T15:22:36.593 回答