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

Retrieving multiple lines of text from the database and populating a TextArea

I am encountering an issue with multi line text saved in a MySql database as VARCHAR 255. When I retrieve and process it using the nl2br PHP function, it displays correctly (with multiple lines). However, when I retrieve the multi line text from the databa ...

Swapping JSON: A Quick Guide

When my Angular code loads, a list of buttons (button 1, button 2, button 3, etc.) is displayed. Upon clicking any button, the console shows J-SON with varying values. Two additional buttons are present on the page for moving up and down. My dilemma arise ...

ASP.net is encountering difficulty locating a specific JavaScript function

Seeking assistance to comprehend the issue, I have devoted countless hours scouring Google for a resolution. Current tools in use: ASP.NET entity framework Within a view, the following code is utilized: <button type="button" id="btnGraf ...

Using NodeJS Script in conjunction with Express and setInterval

Feeling stuck and unable to find clear answers for the best solution. I have a Node.js app that serves APIs with MongoDB as the database. I created a setInterval within the request to update the data every 30 seconds. This was done to prevent the Node.js ...

"Learn the process of incorporating a trendline into a line chart using Highcharts by manipulating the

I am facing difficulties in creating a trend line for a line chart. I have tried some old solutions but they did not work for me. Below is my current code: { "key": "003", "title": "Detections", "ty ...

Any tips on how to retrieve my mesh that has disappeared off the screen?

Struggling to find a way to detect when an element goes off screen, can someone provide guidance? My project utilizes WebGL along with Three.js. ...

Tips on efficiently adding and removing elements in an array at specific positions, all the while adjusting the positions accordingly

My challenge involves an array of objects each containing a position property, as well as other properties. It looks something like this: [{position: 1, ...otherProperties}, ...otherObjects] On the frontend, these objects are displayed and sorted based on ...

Utilize the dimensions of one image to resize others using the JavaScript method .getBoundingClientRect

I am attempting to transfer the width and height measurements of the initial image to all subsequent images on the page. Currently, I have successfully applied the dimensions of the first image to the second one, but I am facing difficulties with the thir ...

Unleashing the potential of Chrome's desktop notifications

After spending the past hour, I finally found out why I am unable to make a call without a click event: window.webkitNotifications.requestPermission(); I am aware that it works with a click event, but is there any way to trigger a Chrome desktop notifica ...

Error message "Index out of range in Swift arrays"

Hello, I'm having trouble printing the elements of an array in reverse order as I keep getting an error that says: Array index out of Range. Could anyone offer some assistance? Below is the code I am using: import UIKit class DecimalToBinaryView ...

Displaying a subset of categories based on the user's selection

I have been trying to find a solution to automatically display a subcategory select drop-down only when a user selects a category. If no category is selected, the subcategory drop-down should remain hidden. I have searched online tutorials and videos for ...

Exploring Ternary Functions within an Associative Array in PHP

I am curious about the possibility and potential lack of side effects when assigning associative array elements using a ternary function in PHP. Instead of the traditional method: $second_element = $test ? "tistrue" : "tisfalse"; echo build_assignment_pa ...

Identifying the floor or ground using a webcam in motion: A step-by-step guide

I am currently facing a unique challenge: In my project, I have markers (specifically Hiro, A, Kanji) displayed on banners, and I need to show a 3D model (such as augmented reality) when the marker is recognized. Everything works well so far, but here&apo ...

Customize button text in Vue using data variable conditions

There are 3 desks in a table with role IDs 2, 4, and 6. In this scenario, two tables are involved. The goal is to dynamically display a specific role name on a button based on the current user's role ID. The desired displays are: If the current use ...

Are the import and export keywords native to webpack or are they specific to JavaScript syntax?

I am pondering whether the import & export aspects are part of the language itself or simply keywords that webpack adds to the language. Thank you. ...

How can you target a specific data-target button while working with multiple Bootstrap collapse elements?

One challenge I'm facing is with the Bootstrap collapse elements on my website. I have several of them, each controlled by a read-more button that includes an icon to indicate the state of the collapse element. However, when I add a class to the butto ...

Why aren't my Post Variables being passed through my jQuery Ajax Request?

My goal is to utilize a full calendar ajax call to add events to the database. After testing the PDO query separately and confirming its functionality, I have identified an issue with the ajax post. The code snippet below showcases the ajax call in defaul ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

Why isn't Material UI Data Grid onCellEditCommit working? Wondering if anyone has insight

Having trouble retrieving the data after editing using onCellEditCommit, but it's not functioning properly. This callback is triggered when changes to a cell are committed. Signature: function(params: GridCellEditCommitParams, event: MuiEvent, deta ...

Disable setTimeout in Node.js triggered by an event

I am facing a dilemma with my code that constantly polls a service and I am looking for a way to efficiently cancel the interval using `clearTimeout` through events. The timeouts essentially act as intervals by calling setTimeout again within the function. ...