clearScreen clearScreen - 21 days ago 5
AngularJS Question

get data from angular.module config to the corresponding controller

I have the following configuration, I have a config where a url is called using $http.get method and the data is stored in a variable "alpha". How do I access this variable from the controller. I tried to inject $rootScopeProvider into the config and tried to set $rootScope.pqr = alpha. This gives an error. How do I do it?

angular.module('thisApp', [someDependencies]).config( function($stateProvider, $urlRouteProvider) {
$http.get('url').then(function(response) {
var alpha = response.data; // i need to access this data in the controller
)};
}).directive('pqrTitle', function () {
return {
restrict: 'A',
controller: function($scope, $rootScope) {

// I need to access alpha here
});
});


How do I do this?

Answer

If you are using ui-router-extras, you can use $futureStateProvider for this, you could also use $rootScope and access it in the controller

angular.module('thisApp', [someDependencies])
.config( function($futureStateProvider, $stateProvider, $urlRouteProvider) {

    $futureStateProvider.addResolve(['$http', '$rootScope', function($http, $rootScope) {
        $http.get('url').then(function(response) {
            $rootScope.alpha = response.data;
        )};
    }]);
})

1) in the controller, you should inject rootScope and access the variable. Read this up to understand the $futureStateProvider in ui-router extras

2) if you do not want to use rootScope, make a service and inject it into teh $futureStateProvider.addResolve, set the variable in the service. After that you can get the variable value through a getter function

Hope it helps