0

I'm very new to angularjs and I want to establish a connection to my server and dynamically show the result to user. so far I've tried:

angular.module('myApp.controllers', []).controller('socketsController', function($scope) {

  $scope.socket = {
    client: null,
    stomp: null
  };

  $scope.reconnect = function() {
    setTimeout($scope.initSockets, 10000);
  };

  $scope.notify = function(message) {
    $scope.result = message.body;
  };

  $scope.initSockets = function() {
    $scope.socket.client = new SockJS('/resources');
    $scope.socket.stomp = Stomp.over($scope.socket.client);
    $scope.socket.stomp.connect({}, function() {
      $scope.socket.stomp.subscribe('/user/topic/messages', $scope.notify);
    });
    $scope.socket.client.onclose = $scope.reconnect;
  };
  $scope.initSockets();
});

But when I use {{result}} nothing appears.

UPDATE The server response is totally right with console.log(message.body).

5
  • any error in browser devtools? Commented Jan 25, 2017 at 13:13
  • No, nothing appears Commented Jan 25, 2017 at 13:13
  • are you resetting the $scope.result any where in the code ? Commented Jan 25, 2017 at 13:15
  • I don't really understand how your code works, but you didn't provide any parameter when you called $scope.notify. Commented Jan 25, 2017 at 13:15
  • try like this $scope.notify = function(message){$scope.$apply(function(){$scope.result = message.body})}; Commented Jan 25, 2017 at 13:21

2 Answers 2

1

I guess, the callback is not taking the scope properly. Try call $scope.$apply(); after you attach the message.body to result :

$scope.notify = function(message) {
    $scope.result = message.body;
    $scope.$apply();
  };

$scope.$apply() triggers an angular digest cycle whcih will update all the bindings..

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. very helpful.
my pleasure :-)
1

Call it inside a timeout function but inject $timeout first it will call the digest cycle and update the value.

$timeout(function(){
$scope.result = message.body;});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.