Search code examples
angularjscontrollerreturn

AngularJS passing data between 2 functions in the same controller


I have a controller which has multiple functions. I need those functions to share some data. For instance, in the code below, my signin function calls the system_connect function from which I want to return http response data back to signin.

Because both these functions are in the same controller, I assumed putting data into $scope.formData in the system_connect function, the same data was be accessible and readable in the signin function - but it isn't working.

headlessQS.controller('mainController', ['$scope', '$log', '$route', '$routeParams', '$location', '$http', '$cookieStore', function($scope, $log, $route, $routeParams, $location, $http, $cookieStore){

    //        signin / register function
    $scope.formData = {};
    $scope.signin = function(){
        console.log('Signin: ');

        $scope.system_connect($scope.formData);
        console.log('Testing Scope.user: ');
        console.log( $scope.connection_response );

        $location.path('/');

    }

    //  drupal system connect
    $scope.system_connect = function(formData){
        console.info('System Connect ...');

        $http.post('http://mysite/angularjs-headless/api/v1/system/connect', 
            {
                'username': formData.username,
                'password': formData.password
            }, 
            {
                'Content-type' : 'application/json',
                'Accept' : 'application/json'
            }
        )
        .then(
//            successCallback,
            function(response){
              console.log('Working ...');
                $log.info(response);
                $scope.formData = response;
            },
//            errorCallback
            function(response){
                console.log('NOT Working ...');
                $log.info(response);
                $scope.formData = response;
            }
        );        
    }
}]);

How might I pass data between two functions in a controller?

Update

Thanks to Sébastien Temprado answer below, I'm beginning to see the light. However, when I implemented the promise, I encountered a problem when I tried checking the contents of $scope.formData. The error is as follows:

(anonymous) @ include.preload.js:628
app.js:39 Uncaught SyntaxError: Unexpected token .

Resulting from the following code:

headlessQS.controller('mainController', ['$scope', '$log', '$route', '$routeParams', '$location', '$http', '$cookieStore', function($scope, $log, $route, $routeParams, $location, $http, $cookieStore){

//    console.debug( $cookieStore.get('user_session') );


    //        re-direct to the sign-in / register form
    $scope.signin = function(){
        var promise = $scope.system_connect($scope.connection_response);
        promise.then({
            console.log("formData:"+JSON.stringify($scope.connection_response));
        });
    }

    //  drupal system connect
    $scope.system_connect = function(formData){
        console.info('System Connect ...');

//        $http.post('/someUrl', data, config).then(successCallback, errorCallback);
        var promise = $http.post('http://mysite/QuestionsGenerator/angularjs-headless/api/v1/system/connect', 
            {
                'username': formData.username,
                'password': formData.password
            }, 
            {
                'Content-type' : 'application/json',
                'Accept' : 'application/json'
            }
        )
        .then(
//            successCallback,
            function(response){
              console.log('Working ...');
                $log.info(response);
                $scope.connection_response = response;
            },
//            errorCallback
            function(response){
                console.log('NOT Working ...');
                $log.info(response);
                $scope.connection_response = response;
            }
        );

        return promise;

    }
}]);

Line 39 is the console.log("formData:"+JSON.stringify($scope.formData)); code. It's the same even if JSON.stringify is taken out and I attempt to log $scope.formData


Solution

  • When you call $http.post(), it's asynchronous (the success callback isn't called immediately) and the execution continue : no more code in system_connect() so it goes back to the signin function(). At this moment, $scope.formData is still empty.

    Then, when you get the response of the post, the success callback is called, $scope.formData is modified but the signin function() has already been executed!

    To solve this problem, you have to use a promise :

    $scope.signin = function(){
        var promise = $scope.system_connect($scope.formData);
        promise.then(function(){
            console.log("formData:"+JSON.stringify($scope.formData));    
        });
    }
    
    $scope.system_connect = function(formData){
        var promise = $http.post('http://mysite/angularjs-headless/api/v1/system/connect', 
            {
                'username': formData.username,
                'password': formData.password
            }, 
            {
                'Content-type' : 'application/json',
                'Accept' : 'application/json'
            }
        )
        .then(
            function(response){
              console.log('Success callback');
              $scope.formData = response;
            },
            function(response){
                console.log('errorCallback');
                $scope.formData = response;
            }
        ); 
        return promise;       
    }
    

    Note

    $http.post returns a promise which is used in the signin function.