Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I initialize module-wide variables?

Tags:

angularjs

I'm trying to do something like this:

angular.module('MyModule', ['ui'])
    .config(function($rootScope) {
        $rootScope.Gender = {
            'M': 'Male',
            'F': 'Female',
            'U': 'Unknown',
        };
    })

But I get this error:

Uncaught Error: Unknown provider: $rootScope from MyModule

If I can't access $rootScope inside my module config, where's the proper place to initialize module-wide variables?

like image 396
mpen Avatar asked Jan 27 '13 22:01

mpen


People also ask

How do you create a module variable in Python?

(If you make a variable inside the Python interpreter, and then import other modules, your variable is in the outermost scope and thus global within your Python session.) All you have to do to make a module-global variable is just assign to a name.


2 Answers

Instead of using $rootScope, you could also use an angular constant or value:

angular.module('MyModule', ['ui']).constant( 'Gender', {
  'M': 'Male',
  'F': 'Female',
  'U': 'Unknown',
});

A constant can never be changed, whereas a value can. And you can inject it wherever you need it:

app.controller( 'MainController', function ( $scope, Gender ) {
  console.log( Gender.M );
});

In my opinion. this seems more "proper" for site-wide variables than using $rootScope.

like image 130
Josh David Miller Avatar answered Sep 20 '22 05:09

Josh David Miller


You can't inject services (here $rootScope) into config block. Only constants and providers can be injected during the config phase.

In your case the correct solution would be to use the run block. Just change config to run and things should be working as expected.

like image 45
pkozlowski.opensource Avatar answered Sep 20 '22 05:09

pkozlowski.opensource