下面我将粘贴我的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订阅方法中更改事件,我怎样才能开火?
答案 0 :(得分:4)
你的回调在angular之外被调用,尝试用$apply
方法包装它以触发摘要周期来确定变化:
$scope.$apply(function () {
$scope.event = JSON.parse(event.body).path + ": " +
JSON.parse(event.body).eventType;
});