Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching global functions and data to $rootScope on initialization in AngularJS

I'd like to have a "Global function" called the first time I launch my AngularJS application, or every time I refresh the page.

This function will call my server with $http.get() to get global information necessary to use my application. I need to access $rootScope in this function. After that, and only after this request finished, I'm using app.config and $routeProvider.when() to load the good controller.

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/', 
        {
            /**/
        });
}]);

I don't want the application do something before this action is finished. So I guess I have to use a "resolve", but I don't really know how to use it.

Any idea?

Thanks!

like image 771
alexmngn Avatar asked Apr 01 '13 22:04

alexmngn


People also ask

How many $rootScope an AngularJS application can have *?

All the $scopes of an AngularJS application are children of the $rootscope. An app can have only one $rootScope.

What is the use of $scope and $rootScope angular object?

Root ScopeAll applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive. The rootScope is available in the entire application. If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.

What is rootScope apply ()?

$scope.$apply() This function is used to execute an expression in Agular. The function expression is optional and you can directly use $apply(). This is used to run watcher for the entire scope. $rootScope.$digest()

What is rootScope broadcast in AngularJS?

$broadcast in AngularJS? The $rootScope. $broadcast is used to broadcast a “global” event that can be caught by any listener of that particular scope. The descendant scopes can catch and handle this event by using $scope.


1 Answers

It's not the best way to solve your given problem, but here is a proposed solution for your question.

Anything inside run(...) will be run on initialization.

angular.module('fooApp').run(['$http', '$rootScope' function($http, $rootScope) {
 $http.get(...).success(function(response) {
     $rootScope.somedata = response;
 });

 $rootScope.globalFn = function() {
   alert('This function is available in all scopes, and views');
 }

}]);

Now an alert can be triggered in all your views, using ng-click="globalFn()".

Be aware that directives using a new isolate scope will not have access to this data if not explicitly inherited: $scope.inheritedGlobalFn = $rootScope.globalFn

like image 180
Kenneth Lynne Avatar answered Sep 16 '22 12:09

Kenneth Lynne