在stomp订阅中更改数据时,Angular JS watch不会触发

时间:2016-11-07 16:51:23

标签: angularjs websocket

下面我将粘贴我的ws连接代码:

function connect() {
    var socket = new SockJS('http://localhost:8080/gs-guide-websocket');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        console.log('Connected: ' + frame);
        stompClient.subscribe('/events/get/1', function (event) {
             $scope.event = JSON.parse(event.body).path + ": " + JSON.parse(event.body).eventType;
        });
    });
}

上面的代码在控制器内部:

myApp.controller('ConnectionController', ['$scope', function($scope) {

以下是我听取改变的指示:

myApp.directive('listenerEventsDirective', function() {
    return{
        restrict: 'E',
        scope: {
            event: '='
        },
        link: function(scope, element) {
            scope.$watch('event', function(newValue, oldValue) {
                if(newValue){
                    element.append("<tr><td>" + newValue + "</td></tr>");
                    alert("newValue " + newValue);
                }
            });
        }
    }
});

如果我在控制器中声明这样的方法:

$scope.changeEvent = function(change){
    this.event = change;
}

一切正常,但如果我尝试通过ws订阅更新我的价值,它将无法正常工作。

即使我在stomp订阅方法中更改事件,我怎样才能开火?

1 个答案:

答案 0 :(得分:4)

你的回调在angular之外被调用,尝试用$apply方法包装它以触发摘要周期来确定变化:

$scope.$apply(function () {
   $scope.event = JSON.parse(event.body).path + ": " + 
      JSON.parse(event.body).eventType;
});