Using Angular Constants to Declare Controller Names
I am trying to declare constants for all string values that I use in my Angular project. My example code looks like below,
//create module
var myApp = angular.module("myApp",[]);
//define constants for controller names
myApp.constant("CONTROLLERS", {
"LOGIN_CONTROLLER" : "loginCtrl",
"HOME_PAGE_CONTROLLER" : "homePageCtrl"
});
Now while creating controllers in their respective controller files I am using the below code,
myApp.controller(CONTROLLERS.LOGIN_CONTROLLER, function(){.....});
When I execute my application I get the following error while loading my loginCtrl.js file,
"Uncaught ReferenceError: CONTROLLERS not defined"
Am I using Angular constants in the wrong way?
Thank.
source to share
Angular constants can only be injected in angular functions
directive('foo', function(CONTROLLERS){});
They cannot be used outside of injection.
Are you trying to use constants because you are not encouraged to leave directive names as strings? Using strings is great because if the name of the directive ever changes, you'll have more serious problems.
Is there some other problem you are trying to solve using constants?
source to share
One solution is to declare constants as a simple javascript variable:
var CONTROLLERS = {
"LOGIN_CONTROLLER" : "loginCtrl",
"HOME_PAGE_CONTROLLER" : "homePageCtrl"
}
This way your code can work.
Here's an example: http://jsfiddle.net/43fu3poz/
source to share