Exploring the Dependency Injection array in Angular directives

After some deliberation between using chaining or a variable to decide on which convention to follow, I made an interesting observation:

//this works
angular.module("myApp", []);
angular.module('myApp', ['myApp.myD', 'myApp.myD1']);

//while this does not work
var app = angular.module("myApp", ['myApp.myD', 'myApp.myD1']);//fails
var app = angular.module("myApp", []);//must use empty DI

This led me to mistakenly believe that there could be a way to achieve the following:

angular.module("myApp", []);
var myDs=new Array('myApp.myD', 'myApp.myD1');
angular.module('myApp', [myDs]);

As I continue to add more directives, I find myself wondering about the best way to organize and manage them. Given a list of directives: myD, myD1..myDn, how do I go about including an array that represents all the directives in the DI array?

Fiddle1: As var Fiddle2: As chained modules

More: Embrace Conventions..they matter

EDIT: Cut and pasted from the angular seed

File One:

angular.module('myApp', [
   'ngRoute',
   'myApp.filters',
   'myApp.services',
   'myApp.directives',
   'myApp.controllers'
])......

File Two:

   angular.module('myApp.directives', []).
       directive('appVersion', ['version', function(version) {
       return function(scope, elm, attrs) {
           elm.text(version);
       };
   }]);

@Baba: Very familiar with both seeds and quoted articles thanks. Note angular seed has only one directive in it, while Josh's seed as far as I can see has no directives. My intent is not to get into the best practice debate but to understand is myApp.directives an array defined somewhere or just the name of the dependency array? Do I place each directive in its own file or all directives under file two?

Answer â„–1

In my experience, I utilize Angular regularly for a large-scale project. Our team has embraced the practice of defining modules through chaining without relying on global variables. This approach helps prevent the creation of overlapping global objects within closures, which can lead to unexpected bugs.

It's important to stick with the Angular module structure as it provides no real benefit to use another approach.

When it comes to organizing modules, there are two main methodologies worth considering: angular-seed and angular-boilerplate:

https://github.com/angular/angular-seed

From my perspective, when working on a large-scale application, utilizing boilerplate may be a more effective way to organize your modules. Additionally, you may find these blogs helpful:

Answer â„–2

Thanks to the insightful reply from m.e.conroy, I was able to find a solution to this question. It seems that each list of dependencies is declared with its own name and added to the Dependency array.

For a scalable solution, using one file per "thing" can greatly alleviate issues for most projects. It's important to note m.e. conroy's advice that "Declaring a global variable in one file and expecting it to be readily available in another just doesn't work or could have unexpected results." So long live no more var declarations for me. This post deserves more attention

// Main Application File
angular.module('myApp',['myDirectives']);

// Directives File
angular.module('myDirectives',[]);

// Directive One File
angular.module('myDirectives').directive('myD', function () {
    return {
        template: 'Similar to ng-include: tag will not work as an element'
    };
});

// Directive Two File
angular.module('myDirectives').directive('myD1', function () {
    return {
        template: 'Similar to ng-include: tag will not work as an element'
    };
});

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

I am experiencing issues with datejs not functioning properly on Chrome browser

I encountered an issue while trying to use datejs in Chrome as it doesn't seem to work properly. Is there a workaround for this problem if I still want to utilize this library? If not, can anyone recommend an excellent alternative date library that ...

Learn how to mock $resource in AngularJS using $promise.then in your jasmine tests

I have a factory that utilizes Angular resource to fetch data from an API. I've developed a function called getObjectById within the service, which uses the factory to request a specific object by ID, then adjusts the object before returning it. Serv ...

Whenever a service is utilized, the form on my controller seems to be out of scope for the service in question

I have the following code factory: angular.module('common') .factory('_g', ['$http', '$q', '$resource', '$rootScope', '$timeout', '_o', '_u', function ($ ...

The not-found.js file in Next.js is displaying an empty page rather than showing a 404 error message

My current project involves using Next.js v13.4.19 with the app router mode. However, I seem to be facing an issue with the not-found.js page located in the app folder. Whenever a non-existing route is accessed, it does not render a 404 page as expected. ...

Checking URL validity using JavaScript Regex

I attempted to validate a URL with or without the http protocol, but no matter what I tried, the function kept returning false. I verified my regex string on this website: And it appeared as expected. function isUrlValid(userInput) { var rege ...

Using the v-for directive in Vue.js to loop through an array and display

Looking at the image provided, I am trying to access the content. I attempted to do so using element.comments.content, but it did not seem to work as expected. Here is the snippet of code: <div class="fil-actualites-container"> <div cl ...

Customizing error messages in Joi validationorHow to show custom

Hi there, currently I am utilizing "@hapi/joi": "^15.1.1". Unfortunately, at this moment I am unable to upgrade to the most recent Joi version. This represents my validation schema const schema = { name: Joi.string() .all ...

Encountering a "Vue is not defined" error in Laravel 5.8 while constructing a comment system using Vue.js

I'm struggling to implement a comment system using Vue.js in my Laravel project. Despite my efforts, I keep encountering a "Vue not defined" error in the console. Can anyone shed some light on why this might be happening? Below is the code snippet I&a ...

Creating resizable rows of DIVs using jQuery

I'm currently developing a scheduling widget concept. The main idea is to create a row of DIVs for each day of the week. Every row consists of a set number of time periods represented by DIVs. My goal is to enable the resizing of each DIV by dragging ...

Use React Router to create a link that goes to the same URL but passes along unique state

Can someone help me figure out how to open the same URL using react-router Link while passing different state each time? <Link to={items.vehicleModelId === 2 ? '/ecgo-3' : items.vehicleModelId === 3 && '/ecgo-5' ...

It appears that Javascript variables are behaving in a static manner

I am currently building a PHP website with a registration page for users. I am implementing the LOOPJ jQuery Autocomplete script from to enable users to select their country easily. In this process, I encountered an issue where the value of another field ...

Distribute Test Specifications Across Nodes Using Protractor and Selenium Grid

After setting up a Selenium Grid with one server for the hub and 10 other servers hosting one node each, my Protractor automated tests are running smoothly. However, I am looking to distribute my approximately 400 tests across all defined nodes in multiCap ...

Error receiving parameter in express route callback function

At the moment, I have been working with a number of routes in Express. Some routes are quite lengthy and tend to look like this: router.get('/api/comments', function(req, res, next){ Comment.find({"user": req.payload._id}).exec(function(err,co ...

Navigation Bar Dropdown Menu Not Responding to Clicks

I'm having trouble implementing a dropdown menu in my navigation bar that should appear when the user clicks and disappear when they click anywhere outside of it, similar to Facebook's dropdown menu with options like logout. However, for some rea ...

What is the process of adding an array into a JSON object using the set() function in Firebase?

I am trying to add a new item to my firebase database with a specific JSON object structure: var newItem = { 'address': "Кабанбай батыр, 53", 'cityId': 1, 'courierName': "МаР...

How to redirect in Next.js from uppercase to lowercase url

I'm trying to redirect visitors from /Contact to /contact. However, following the instructions in the documentation results in an endless loop of redirects. This is my attempted solution: // next.config.js async redirects() { return [ { ...

Eliminate FormData usage from the Next.JS backend application

Looking to replicate the steps outlined in this guide: https://medium.com/@_hanglucas/file-upload-in-next-js-app-router-13-4-6d24f2e3d00f for file uploads using Next.js, encountering an error with the line const formData = await req.formData();. The error ...

Eliminate item from array based on certain criteria

In certain scenarios, I must update the filters. Under specific data conditions, I am required to eliminate 1 item from an array. Here is the code snippet: useEffect(() => { let canceled = false; const filters = [ new C ...

"Android Webview's evaluateJavascript function is not returning the expected value

I am attempting to retrieve the username from a webview, but it is returning a null object. webView.settings.javaScriptEnabled = true webView.evaluateJavascript( "(function() { return document.getElementsByClassName('lgn-loginname') })() ...

Echo the date while using the foreach function to list arrays together

Is there a way to sort articles by Date instead of just Name? Directory structure: Blog/2019/articleDirA, Blog/2019/articleDirB,... Blog/2018/articleDirA, Blog/2018/articleDirB,... Each article directory (ex. articleB) contains these files: data.php ...