0

I'm trying to pass data from a service to a controller in angular js, the code is the following:

.controller('lista',function($scope,cetrams){
    $scope.hola="This is it";

    var test;
    var testfn = function(){
        test = 'Lala';
    };

    cetrams.success(function(data){
        testfn();
        test = data;
        console.log('Inside service: '+test);
    });

    console.log('Inside controller: '+test);

})

The service is working, as I get the promise and the function for success is executed, but I cannot get the variable outside that function to the controller scope.

1
  • I cannot answer my own question but I already figured it out, what happens is that console.log from outside runs sequentially without waiting for the promise to success, but the actual scope variable is effectively updating. Commented Jan 28, 2014 at 12:15

1 Answer 1

2

If you are expecting the value to be available at the last line

console.log('Inside controller: '+test);

then you are incorrect. Due to async nature of the code the last line would get executed before the service returns with data.

Your logic should be done in the success method or use $scope.$watch to watch the test variable for change

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

1 Comment

Thanks, I realize it after post it and try to answer the question but I can't as I don't have enough points.

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.