What are the implications of employing a singular global variable for angular modules?

After coming across a template, I noticed that the variable anApp is declared once in app.js and then shared among all modules. This has led me to wonder: 1. Will using a single variable result in all Angular components being stored in the global scope? 2. Is this approach considered an anti-pattern or an acceptable design pattern? If it is discouraged, does anyone have suggestions for a best-practice alternative?

Thank you

---app.js----
 var anApp = angular.module("myApp", [
    "ui.router", 
    "ui.bootstrap", 
    "oc.lazyLoad",  
    "ngSanitize"
]); 

anApp.config(['$ocLazyLoadProvider', function($ocLazyLoadProvider) {...}]);

---controllers.js---
anApp.controller('fooCtrl', ['$scope', function($scope) {...}]);

---directives.js---
anApp.directive('ngSpinnerBar', ['$rootScope',function($rootScope) {...}]);

etc.

Answer №1

For small-scale applications, it is possible to manage with just a single module. By following common examples and utilizing a global variable, there is no need to constantly search for modules by name. Adding one extra global variable is not a significant issue, especially if it has a recognizable name like the "app" module for anyone reviewing your code.

However, maintaining only one module for a medium to large-sized application goes against best practices. It is not only inefficient but also illogical to create a module for every individual component (such as a controller). While it may seem excessive, organizing modules based on artifact type ('myControllers', 'myDirectives', etc.) could be more beneficial than having none at all.

The key is to identify and establish modules in a logical manner:

  • Which components should be grouped together?
  • Are there any dependencies between artifacts and modules?
  • Does the dependency structure resemble a tangled mess or a structured tree?
  • Are there standalone units that could exist in a separate web application?
  • Could any artifacts be shared as an open-source module?
  • Can the application be divided into vertical (login, user-admin, statistics) or horizontal parts (access-layer/caching, logic/communication, UI)?

In a medium-sized application, it is typical to have around 10-30 modules. Some of these modules (~10) may be reusable in other projects, while others are specific to the domain. The ideal number of modules varies depending on the app's size and desired granularity. Having fewer than 30 modules allows for easier management without getting lost in complexity.

Regarding other concerns: In Angular 1.3, the number of modules does not impact the application once it is loaded. There is a single injector where all artifacts are injected using their unique names (except for directives, which can share names). Angular avoids cluttering the global scope with new variables by referencing artifacts from the injector "registry."

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

``Is there a more SEO-friendly option instead of using an iframe?

I am looking for a solution to easily share my content with other websites without the issues I currently face. Presently, I use an iframe which poses two problems: <iframe width=“540”; height=“700” frameborder=“0” src=“http://www.energi ...

Why does tween animation appear instant rather than smooth?

I am trying to achieve a camera movement effect where the camera transitions from its current position to the center of a mesh (which is a sphere and I want to be inside of it) when a button is clicked. I have implemented a function with a tween for this ...

Integrate Javascript code into a JavaScript file

Is there a way to incorporate a JavaScript link inside a .js file? Does a .js file support include, require, or import similar to CSS or PHP? Here is the code in question: // Global site tag (gtag.js) - Google Analytics var script = document.createElemen ...

Issue: missing proper invocation of `next` after an `await` in a `catch`

I had a simple route that was functioning well until I refactored it using catch. Suddenly, it stopped working and threw an UnhandledPromiseRejectionWarning: router.get('/', async (req, res, next) => { const allEmployees = await employees.fi ...

Webpack creating a bundle file with no content

I'm currently facing a challenge with webpack/webpack-stream while trying to bundle some JavaScript files. The issue I am encountering is that, despite generating the bundle.js file, it turns out to be empty. To ensure clarity, I've provided the ...

Show a malfunction with the `show_message` function

How can I show the die() message in if($allowed) in the same location as the move_uploaded_file result? <?php $destination_path = $_SERVER['DOCUMENT_ROOT'].'/uploads/'; $allowed[] = 'image/gif'; $allowed[] = ' ...

When Angular UI Bootstrap Carousel and Tabs overlap on a single page

Currently, I am utilizing Angular UI Bootstrap for a project involving AngularJS. Within this project, I have implemented both a Carousel and Tabs on the same page. A challenge that I am facing is that the Tabs are switching along with the Carousel slides ...

How to leverage async/await within loops in Node.js for optimized performance and efficiency

Hey there, I'm working on my nodejs api where I need to fetch data inside a loop and then perform another loop to save data in a different table. Can anyone guide me on how to achieve this? Below is a snippet of what I have attempted so far without su ...

Create a BezierCurve dynamically using Three.js

I'm struggling to dynamically generate a BezierCurve from arrays in JavaScript. I tried using push method, but it's not working as expected. var x = [0,10,100,220,100, etc,...]; var y = [10,0,100,200,200, etc,...]; var z = [100,220,10,0,100, etc ...

Interacting with a 3D model using the mouse cursor in a three

After stumbling upon the three.js library recently, I've been spending several days experimenting with it. I am eager to incorporate a mouse event into my project similar to this example where the head of the skull follows the cursor. However, I want ...

Using JavaScript to calculate the difference between the current hour's value and the previous hour's value

Just started experimenting with JavaScript yesterday and was given a small task to create a script for a building controller. The task involves reading values from specific locations, performing energy calculations, and then after 1 hour, subtracting the i ...

What is the best way to display the contents of an array that contains another array within it?

I need help looping through this array and displaying the "roleName" value. I want to use the map method to iterate over it. { "userMenuDTO": { "menuId": "13", "menuName":"PruebaMenu900 ...

Server with minimal setup requirements

While developing my Angular projects, I rely on lite server. This tool utilizes BrowserSync for tasks such as serving the site to localhost and enabling live reload functionality. In my project's root directory, there is a configuration file named bs ...

Grant permission for site A to access site B

These days, the commonly used term is "Single Sign On". Let me explain my situation. I apologize if I am using incorrect terms or if my explanation is unclear, as I am not an expert developer or architect. I have Site A (e.g., www.siteA.com) and Site B ...

How can I connect HTML and JavaScript to get the clicker functioning?

While the HTML and javascript work flawlessly on jsfiddle where I initially created this project, I'm encountering a problem with Google Drive's hosting. The HTML displays correctly but there is no interaction happening with the javascript. Belo ...

Vue JS - Toggle visibility of an element based on radio button selection

When selecting between true or false radio buttons, I want a block to appear when "One" is clicked and be hidden when "No" is clicked. Here is the code snippet I used: <template> <div> <div> <label >One & ...

The color of the progress bar in JS is not displaying properly

My work involves using jQuery to manipulate progress bars. The issue I am facing is defining standard colors that should be displayed on the progress bar based on the value received. Here is my code: var defaultSegmentColors = ['#FF6363', &ap ...

Sharing a const object across different pages in React

I have implemented this code snippet to translate the content on my website. Is there a more efficient way to apply this translation functionality without having to manually copy and paste the code across multiple pages? import SampleSection from ". ...

Counting and Arranging Numerous Commitments in the World of Javascript

I’m faced with a challenging scenario that’s got me puzzled: -I’ve got an array of 10 objects, each with two properties: IDNum and imageURL. -Only 3 of these objects actually have their imageURL property set (at index positions [0, 4, 9]), and n ...

Guide to retrieving the second value variable in an array based on the selected dropdown option within a controller

In my controller, I am trying to extract the second value in an array list that a user selects from a dropdown so that I can perform mathematical operations on it. $scope.dropdown = [ {name:'Name', value:'123'}] When a user chooses "N ...