Best practices for defining module-wide constants in AngularJS

In my project, I have around 20 "modules" each with its own unique functionality but following the same structure. These modules are stored in separate files within their respective folders. For instance, the admin module is located in the modules/admin folder and includes the following files:

admin.module.js
admin.routes.js
admin.content.jade
admin.content.controller.js
admin.content.controller.spec.js
admin.sidebartop.jade
admin.sidebar.controller.js
admin.sidebar.controller.spec.js
and more......

All files across different modules share a common code structure enclosed within an immediately invoked function expression (iife).

To ensure error-free coding and facilitate easy structure reuse, it is necessary to define specific constants for each module and utilize them in controllers, routes, etc.

Although I am familiar with the module.config and constant functionalities, they do not solve the issue since reusing the same constant name twice is not allowed. This implies some parts of the code need rewriting even when untouched.

angular.module('app.foo').constant('CONST', {...}) 

would clash with

angular.module('app.bar').constant('CONST', {...})

Therefore, I devised a solution which functions well but feels somewhat inadequate.:

I centralize all static configurations in the *.module.js file

    (function () {
    'use strict';

    angular.module('app.admin', [
        'app.foo',
        'app.bar'
    ]).CONST ={
            module: 'Admin',
            state: 'admin',
            url : '/admin',
            path: 'app/views/modules/admin/',
            title: 'Admin',
            description: 'This is the admin module',
            acl: ['Developer','Administrator'],
            tileGroups: ['Company'],
            icon: 'mif-books',
            badge: 0,
            filters :
                {'rootNodes' :{where: {'Template.value' : 'Admin'} } },
            ready : false
        };
    })();

I then reuse this configuration in *.routes.js:

    (function () {
        'use strict';

        var module =angular.module('app.details');
        var CONST = module.CONST;
        module.run(appRun);

        appRun.$inject = [ 'routerHelper'];
        /* @ngInject */
        function appRun( routerHelper) {
            var states = [{
                state: CONST.state,
                config: {
                    title: CONST.title,
                    url: CONST.url,
                    acl: CONST.acl,
                    templateUrl: CONST.path + CONST.state + '.content.html',
                    controller: CONST.module + 'ContentController',
                    controllerAs: 'vm',
                    ncyBreadcrumb: {
                        label: CONST.module
                    }
                }
            }
            ];
            routerHelper.configureStates(states);
        }
    })();

Furthermore, in all my *.*.controller.js files :

(function () {
    'use strict';

    angular
        .module('app.admin')
        .controller('AdminContentController', AdminContentController);

    AdminContentController.$inject = ['foo', 'bar'];
    /* @ngInject */
    function DetailsContentController(foo, bar) {
        var vm = this;
        _.extend(vm, CONST); // for re-usage in my jade / html files

        // ACTUAL CODE GOES HERE
    }
})();

This methodology aims to minimize alterations required in individual files when making changes on a module-wide level.

For example, if I alter the title from 'Admin' to 'Administration', I only need to make the change in one place instead of multiple files using the title. Additionally, my spec.js files are automated so tests remain intact even after modifying settings.

Is there a more elegant, angular-centric approach to address this challenge?

Answer №1

Implement constant():

(function () {
'use strict';

angular.module('app.management', [
    'app.users',
    'app.roles'
]).constant('CONFIG', {
        module: 'Management',
        state: 'management',
        url : '/management',
        path: 'app/views/modules/management/',
        title: 'Management',
        description: 'This is the management module',
        acl: ['Developer','Manager'],
        tileGroups: ['Company'],
        icon: 'mif-boxes',
        badge: 2,
        filters :
            {'rootNodes' :{where: {'Template.value' : 'Management'} } },
        ready : true
    });
})();

Then access it by injecting CONFIG. Example:

function ManagementController(users, roles, CONFIG) {...}
ManagementController.$inject = ['users', 'roles', 'CONFIG'];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Improve your JavaScript form by implementing a time loading feature!

I am currently developing a sign-up form using native JavaScript and Ajax. The form utilizes an Ajax function to transmit data to a PHP engine, which then performs database queries. My main concern is implementing a loading function in JavaScript that can ...

Uploading files on a web page using AJAX technology

I'm attempting to perform a file upload on an ajax response page. The main.php file contains basic ajax code as shown below: <html> <head> <script type="text/javascript"> function loadXMLDoc() { var xmlhttp; if ...

What is the best way to switch back and forth between two div elements?

I've been attempting to switch between displaying div .cam1 and div .cam2, however, I can't seem to get it to work. Here's the code snippet in question: HTML: <div class="cam1"></div> <div class="cam2"></div> CS ...

Alter the responseType within Angular (5) once the response has been received

Is it possible to dynamically change the response type in the post method (angular 5) after receiving the response? The challenge: I need the response type to be blob when the response is successful, and json when there's an error. I've searc ...

Integrating data binding within a .append function using AngularJS

I followed this code example (http://jsfiddle.net/ftfish/KyEr3/) to develop a form. However, I encountered an issue with an input having ng-model set to "value" and needing to display that value within {{ }} in a TD: angular.element(document.getElementByI ...

There is an array present with data filled in, but unfortunately, I am unable to retrieve specific elements

As I work on my WordPress 4.7.2 website, I find myself making an AJAX call. The PHP function handling this call returns an array using wp_json_encode(). When I view the data array in the success callback of the AJAX function, everything looks just as expec ...

Angular 8 combined with Mmenu light JS

Looking for guidance on integrating the Mmenu light JS plugin into an Angular 8 project. Wondering where to incorporate the 'mmenu-light.js' code. Any insights or advice would be greatly appreciated. Thank you! ...

Troubleshooting: Issues with locating CSS and JS files (404 error) while utilizing URL parameters within Django platform

I've designed a dashboard page that showcases various graphs. The page automatically updates the graph data every hour. You can access the page at the following URL: http://localhost/dashboard I'd like to give users the option to specify the ...

Getting to a nested key in a JSON object with JavaScript: a step-by-step guide

Currently, I'm working with a JSON file and need to extract the fileName tag for use. { "dataset": { "private": false, "stdyDscr": { "citation": { "titlStmt": { "titl": "Smoke test", "IDNo": ...

Tips for handling a JSON payload retrieved through a POST request

I'm currently working on a button that triggers a POST call to retrieve a json response from the server. My goal is to display this json response in a new (chrome) browser tab. Here's what I have so far using Angular: $http.post(url, data) .t ...

What steps can I take to allow a third-party JavaScript to access my TypeScript object?

I am working on an Angular application and I have a requirement to develop an API for a third-party JavaScript that will be injected dynamically. public class MyApi{ public callSomeFunction():void{...} public getSomeValue():any {...} } var publicA ...

Troubleshooting issues with jQuery `.live()` event not triggering as expected

In a project I am working on, I have implemented complex AJAX functionality to fetch inner page content from a WordPress blog. Due to the dynamic nature of the site, where the DOM is replaced after page load via AJAX, I have opted to use jQuery's .liv ...

Error message: "The property or method you are trying to access is not defined

I had no issues with my app until I added the JavaScript, now I'm getting constant errors in the console. One of the errors I see is: Property or method "show" is not defined on the instance but referenced during render. Make sure that this proper ...

Is it possible to utilize one controller within another controller in angularjs?

I am interested in using the Angular JS scrollbar to display content. Here are the controllers I plan to utilize: module.controller('itemsCtrl', function($scope){ $scope.items = [ {src:'../static/images/image-3.png&apos ...

What is the correct way to pass the res object into the callback function of a jest mock function?

Currently, I am working on developing a web server using Node.js and am in the process of ensuring comprehensive test coverage with Jest. One specific function, logout, requires testing within the if statement where it checks for errors. // app.js functio ...

The negation functionality in the visible binding of Knockout.js is not functioning properly

I'm having trouble using the visible data binding with a negation and it's not functioning as expected. I've come across various posts on stackoverflow suggesting that the NOT binding should be used as an expression. However, in my scenario, ...

Combine various canvases into a single one (for exporting purposes) with pure Javascript

I'm currently faced with a unique challenge involving the creation of around 200 canvases, each showcasing an image captured from the user's webcam as part of an experimentation process for the "photo finish" technique. My task now is to export ...

Having issues with jQuery when trying to select only a single checkbox?

I have created a table with four rows and eight columns, each containing a checkbox. My goal is to allow only one checkbox to be checked per row. I am attempting to achieve this using jQuery. While it works in jsfiddle, I am experiencing difficulties in ge ...

In what way does s% access the title attribute within the Helmet component?

I am seeking clarification on how the reference to %s is connected to the title attribute of the <SEO /> component within the <Helmet /> component in the gatsby starter theme. Can you explain this? Link to GitHub repo On Line 19 of the code: ...

Inquiry regarding the process of object creation in JavaScript

I recently discovered a method to create your own 'class' as shown below: function Person(name, age){ this.name = name; this.age = age; } Person.prototype.foo = function(){ // do something } Person.prototype.foo2 = function(){ ...