angularjsrootscope

Make function in rootscope return in scope


I have made a rootscope function with a attribute. it is getting some data from a the db.

I want to use this rootscope function in a controller and put the data what i get in a variable.

$rootScope.get_option = function(option_name){
        $http.post("server/read.php",{'subject': "options", "args": option_name })
        .success(function (response) {
            console.log(response);
            $rootScope.option_get_value = response;

        });

        if($rootScope.option_get_value){
            return $rootScope.option_get_value;
        }

    }

And this i what i have in the controller

    $scope.subscription.reduced_hourrate = $rootScope.get_option('verlaagd_tarief');
    console.log($scope.subscription.reduced_hourrate);

When i run the script, i see in the logs $rootScope function giving me correct value back. But the scope is giving me undefined data back.

Why is this happening? and someone help me of give me some tips?


Solution

  • $http makes an asynchronus call. That means your if statement if($rootScope.option_get_value) ... is called before your http success function is resolved.

    To make it work you can do it this way

    $rootScope.get_option = function(option_name){
        return $http.post("server/read.php",{'subject': "options", "args": option_name })
    }
    

    Then inside your controller

    $rootScope.get_option('verlaagd_tarief').success(function (response) {
         $rootScope.option_get_value = response;
    });
    

    But I'm not sure this is the best way to pass data to a controller. A common way is to use services. Without using $rootScope

    Here is an example how to use of services to pass data to a controller.

    var app = angular.module('myApp', []);
    
    //declare a service that make the http calls
    myApp.factory('myHttpService', function($scope, $http) {
    
       //return the public API
        return {
            //use a callback function to return
            //the result when the promise is resolved
            get_option : function(option_name, fct){
                $http.post("server/read.php",
                     {
                          "subject": "options", 
                          "args": option_name 
                     }
                ).then(function(result){
                    fct(result) //calling the callback when the promise is resolved to return the result
                })
        }
    });
    
    // the controller using myHttpService
    myApp.controller('myCtrl', function($scope, myHttpService) {
       myHttpService.getOption('verlaagd_tarief', function(result){
           $scope.option_get_value = result
       })
    });