What is the reason behind Angular (1.x) permitting a module's dependency to directly reference its components?

Take a look at this code snippet:

angular.module('app', ['app.core'])
    .factory('NameService', function() {
        return {
            getName: function() { return 'Omar' ;}
        };
    });
       

angular.module('app.core', [])
    .controller('MainController', function($scope, NameService) {
        $scope.name = NameService.getName();
    });
<body ng-app="app">
    <div ng-controller="MainController">
        {{name}}
    </div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
</body>

The output will show "Omar". Although NameService is defined in the app module which is not listed as a dependency of the app.core module. It might seem like there could be circular dependencies, but it still works. Why is that?

Answer №1

Simply put, in every angular application, there is a single `$injector`. Whenever a dependency is registered, its signature gets added to the `modules` Array within the `$injector`. When a specific dependency is called upon, its signature is fetched from this array. It's important to note that the `$injector` does not limit access to the `modules` array based on where the registration occurred; all registered dependencies are accessible throughout the entire application.

Answer №2

Angular 1.x has a flaw in its design that relies on a global registry for all services, controllers, factories, directives, and more. When a module is "installed," it adds its components to this registry using their names as keys. This means a module can function even if it doesn't explicitly register its dependencies, as long as another module does so.

In large Angular applications, this approach can lead to common errors where undeclared dependencies are used unintentionally. Rearranging the module structure of your app can unexpectedly break things due to these hidden dependencies.

Angular 2's module system addresses this issue more effectively and improves upon the design of Angular 1.x.

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

AngularJs: Issue encountered while compiling an ng-switch statement

Programming <input type="text" ng-model="user.name" /> <div ng-switch on="user.name"></div> <p ng-switch-default>The winner is</p> <h1 ng-switch-when="John">{{ user.name }}</h1> Can anyone help me? I encountered ...

requesting headers using AngularJS for JSON data

By performing this action, I can retrieve some data .. However, it is not in JSON format. var url = 'inputtest.php'; $http({ method: 'POST', url: url, data: $.param($scope.company), headers: { 'Content-Type': 'applicatio ...

How to run a PHP script using JavaScript?

I am planning to execute a quick php script once users exit my website. Moreover, I am looking to transfer a variable from my javascript to php, but I am unsure how to integrate the php file and pass it a variable. Unfortunately, the php script is not runn ...

Encountering a "Connection Refused" error when attempting to test a React and Express application

Currently, I am developing an order system using React for the frontend (port 3000) and Express for the backend (port 3001). Everything functions perfectly when tested on the same MacBook that hosts the node project. However, when testing it on a differen ...

Error: Next.js is experiencing a duplication of CKEditor modules

Here's the current code snippet I am working with: import { useEffect, useState, useRef } from "react"; function TextEditor({ token }) { const editorRef = useRef(); const [editorLoaded, setEditorLoaded] = useState(false); const { CKEd ...

Send the Post model along with 2 checkbox lists to the controller using Jquery's Ajax function

How can I efficiently send 2 lists containing values of checked checkboxes along with my model using JQuery Ajax from an EditorTemplate used as a partial view? Here's the code snippet: @model EsdpExport.View_Models.ProductLineCreateViewModel @using E ...

Issues with looping in Internet Explorer 8

Hey, I'm having an issue with this JavaScript function: function test(){ var count = 0; var date1 = $('#alternatestartdate').val(); var date2 = $('#alternateenddate').val(); ...

Using a custom function, automatically initiate audio playback when an Android WebView JS loads

I have a unique JS function specifically designed for the audio tag, which also controls the progress bar. It works perfectly when I click on the associated tag <a onclick="playSound(1)">. However, if I try to initiate it on page load, the function s ...

The email message generated by sendGrid is kept confidential

When attempting to send emails using Node.js with SendGrid, I am experiencing an issue where the email content is always hidden. Here is my node.js code: const msg = { to: 'example@example.com', from: 'sender@example.com', ...

Unexpected symbols appearing in image tag after AJAX response

I'm currently grappling with an issue related to an AJAX request I am working on (I am quite new to the world of AJAX). I have set up an API and my goal is to fetch a PNG image using an Authorization header that requires a token supplied by me (which ...

Is there a way to utilize localStorage to retain a classlist toggle status for a light/dark mode theme switch on the browser?

I am currently working on a portfolio website that features a light/dark mode theme switch. The functionality of the switch is working properly, but it doesn't save the user's preference when they refresh the page or navigate to another section. ...

How can one iterate through elements of a specified length using Jquery?

Currently, I am in the process of designing an animation for my website. The animation involves different divs that each contain an image and a description related to that image within an aside element. The width of the aside is slightly wider than the ima ...

Can you guide me on switching between windows using the selenium IDE?

Instructions for handling popup windows in Selenium 2 (WebDriver) can be found at the following link: The instructions state that testing popup windows in Selenium 2 involves switching the driver to the popup window and then running the corresponding acti ...

Effective methods for synchronizing two dropdown menus with varied displays using React

Having a list of countries with specific key-value pairs, I am interested in creating two Dropdown lists. The first will display the keys, while the second will show the corresponding text values. The main objective is to provide the option to select eith ...

Upon clicking close, the icons do not appear as expected

Currently, I am developing an application using Next.js. In this application, there is a functionality where clicking on the hamburger icon in mobile mode hides the icons of a Slide, and upon closing the hamburger, they should reappear. The overall struct ...

Verify the authenticity of angularjs and enroll in classes

Recently diving into the world of Angularjs, I'm pondering on the best approach to create a basic app allowing users to subscribe to courses... Where should I store these subscription records? Is saving them in a json file on the server secure enough ...

Tips for choosing at least three files in file upload control

How can I choose at least three files in a multiple file upload control? Should I integrate an AJAX FILE UPLOAD CONTROL TOOL KIT? I need to select a minimum of three files for the file upload control. If fewer than three files are selected, I want an ale ...

Determine which submit button was clicked during the validation process

Currently, I am in the process of developing a new custom validator for MVC4. I have experience with this task and have successfully completed it several times before. However, this time around, I am faced with a new challenge - I need to determine which s ...

Scripts for Azure mobile services

As a newcomer to server scripts, I am facing an issue that I believe has a simple solution, although I have been unable to find the answer so far. My current setup involves using azure mobile services for retrieving and inputting user information, with a f ...

I'm unable to adjust the price to meet the quantity of units needed

$.ajax({ dataType: "json", url: "https://private-70cb45-aobara.apiary-mock.com/product/list", success: data =>{ const price = data[0].unitPriceInCents; var quantity = 1; //PRICE $("#Product-Price").text("$ " + data[0].unitPriceInCe ...