Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Basically i have two sources of data, one is real time data from socket.io and other is json object. And i'm using both in front-end but the problem is that i need to pass a variable from socket.io to json parser:

This controller for my view:

.controller('mainCtrl', ['$scope','socket','currentData', function($scope, socket,         currentData){

    // It's updated every 2 seconds
    socket.on('chnl', function(data){
         // Passed to view OK
         $scope.realtimeData = data;

         // And i need to pass this to currentData.
         $scope.foo = data.foo;
    });

    // Here i'm getting json response from factory which is computed based on socket.io foo variable and then passed to view. 
    currentData.get().then(function(data){
         if($scope.foo)...
         ...
         $scope..
    });


}]

The problem is anything i tried i ended up calling json object on every incoming socket.io package, what i need to calc this at it's initalization and pass data to the view.

Any solutions?

Thanks.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

If you need for it to run only once for initialization...

Move the call to the JSON service into the .on callback. Place it inside of a conditional which runs only when an initialization variable is set to false. Once the data is set, switch that variable to true so that it doesn't run again:

.controller('mainCtrl', ['$scope','socket','currentData', function($scope, socket, currentData){
    $scope.fooInit = false;

    socket.on('chnl', function(data){
        $scope.realtimeData = data;
        $scope.foo = data.foo;

        if (!$scope.fooInit) {
            currentData.get().then(function(data){
                if($scope.foo)...
                 ...
                $scope..
            });
            $scope.fooInit = true;
        }
    });
}])
share|improve this answer
    
Perfect! Thanks :) –  Jack Jun 1 at 10:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.