简体   繁体   中英

Define a constant that can be used in module/controller/etc. definition in angular

I would like to put module name, controller name etc. to string constants, so that I can easily change them if the need be (compared to fixing it in each and every file).

So I have this code:

 angular
    .module("app.admin.home")
    .controller("HomeController", HomeController);

And I would like it have this (or similar):

 angular
    .module(moduleConstants.admin)
    .controller(controllerConstants.adminHome, HomeController);

Is there a proper way to define this type of constants in Angular (ordinary injection does not work in this case). I guess I can create just global javascript constants, but maybe there is a better way of achieving this, some common way to define constants in angular. I have a strong C# background and it sounds stupid to me that constants need to be injected, they are not abstract code that can have different implementation, so it sounds wrong to inject it rather than just reference.

To avoid polluting the global name space, you could use a closure:

(function (moduleConstants, controllerConstants) {
    angular
        .module(moduleConstants.admin)
        .controller(controllerConstants.adminHome, HomeController);
})({admin: "app.admin.home"},
   {adminHome: "HomeController"});

According with the documentation, the right way of defining constants using angular js is using: Constants

This can be a simple implementation:

angular.module('config', [])
    .constant('CONSTANT_YOU_NEED', {
        name: 'test',
        valueOfConst: '3.14'
    });

But i guess you can't use this for modules or Controllers, but just passing to them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM