Kamil Banaszczyk Kamil Banaszczyk - 1 month ago 11
AngularJS Question

Angular JS watch won't fire when data is changed in stomp subscribe

below i will paste my ws connection code:

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


And this code above is inside controller:

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


And below is my directive to listen on change:

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


If i declare method like this in controller:

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


everything is working, but if i try to update my value through ws subscribtion it won't work.

How can i make watch fires even if i'm changing event in stomp subscribe method?

Answer

your callback is called outside angular, try wrapping in an $apply method in order to trigger a digest cycle to determine changes:

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