What is the reason for injecting dependencies twice in AngularJS?

I'm a beginner in Angular and I'm curious to understand the reasoning behind injecting all our dependencies twice. Here is an example:

var analysisApp=angular.module('analysisApp',[]);

analysisApp.controller('analysisController',function($scope,$http,$cookies,$state,globalService){   

});
However, the code can also be written like this:
var analysisApp=angular.module('analysisApp',[]);

analysisApp.controller('analysisController',['$scope','$http','$cookies','$state','globalService',function($scope,$http,$cookies,$state,globalService){ 

}]);
But why do we need to do this?

Answer №1

To ensure the app is secure, it needs to be made minsafe.

Caution: When minifying your code, be aware that dependency names may be altered and could potentially disrupt the functionality of your app.

When you choose to minify all files, the dependencies will be replaced with generic terms like a, b, etc.

However, by using array and string syntax, as demonstrated in the following example, certain elements like string are not subject to minification and can be utilized for mapping purposes. This allows the app to recognize that a corresponds to $scope(View example below).

Example:

// Once minified
var _ = angular.module('analysisApp', []);

_.controller('analysisController', ['$scope', '$http', '$cookies', '$state', 'globalService', function (a, b, c, d, e) {
    a.name = 'John Doe'; // Now 'a' refers to `$scope`.
}]);

Refer to Angular Docs for more information.

Check out this helpful article on achieving minification safety with Grunt.

For best practices in minification, visit: Angularjs minify best practice

Answer №2

Angular's implementation of dependency injection involves converting the function into a string and identifying its arguments. However, this method is problematic when minifying your code because variable names can become mangled, leading to malfunctions in your application. To address this issue, Angular allows you to specify the names of these injections using strings to prevent them from being mangled. In essence, after minification, your code might resemble the following:

analysisApp.controller('analysisController',
['$scope','$http','$cookies','$state','globalService', function(a,b,c,d,e) {

}]);

Internally, Angular will correspond $scope to a, $http to b, and so forth.

Alternatively, you can utilize ngannotate, a pre-processor tool that can be integrated into your build process. This tool transforms the initial code snippet into the annotated version mentioned above.

Answer №3

var app=angular.module('app',[]);

app.controller('controller',['$scope','$http','$cookies','$state','service',function($scope,$http,$cookies,$state,service){ 

}]);

When minifying this code, it may look like:

var app=angular.module('app',[]);

app.controller('controller',['$scope','$http','$cookies','$state','service',function(a,b,c,d,e){ 

}]);

In this scenario, a, b, c, d will hold references to

'$scope','$http','$cookies','$state','service'
respectively and everything will function as expected.

The values of

'$scope','$http','$cookies','$state','service'
remain unchanged during minification since they are strings.

app.controller('controller',function($scope,$http,$cookies,$state,service){   

});

However, after minification, the above code may transform into:

app.controller('controller',function(a, b, c, d, e){   

});

At this point, Angular objects such as $scope lose their original meaning and the functionality breaks down.

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

How to maximize efficiency by utilizing a single function to handle multiple properties in Angular

I have 2 distinct variables: $scope.totalPendingDisplayed = 15; $scope.totalResolvedDisplayed = 15; Each of these variables is connected to different elements using ng-repeat (used for limitTo) When the "Load More" button is clicked (ng-click="loadMore( ...

Is there a way to transfer parameters from a Vue function to a component?

I am struggling to find the right solution for passing parameters to a function. I need to use NavigateTo to send a String value to my index in order to switch components without using Vue Router. Home.js Vue.component('Home', { props: [&apo ...

Issues with React router arise once the app has been built

I am new to utilizing react and react-router in my project. I have built the application using create-react-app and now I am facing an issue with routing between two main pages. After trying different approaches, I managed to get it working during develop ...

What is the fallback mechanism in Astro js when the cache is unavailable?

When the cache is not accessible in Next.js, the page will be server-side rendered and displayed using either the true or blocking fallback approach. I am curious about the approach taken by Astro.js in this situation. I am planning to develop a dynamic b ...

Binding an event to an Angular 2 component directly within its selector code

Looking at my Angular 2 component: import { Component, ElementRef, Renderer } from '@angular/core';; @Component({ selector: 'my-button', templateUrl: 'button.html' }) export class ButtonComponent { private text: string ...

Function cannot be called upon directive initialization

I'm currently developing a custom directive in AngularJS and I am facing an issue with calling a function upon loading my directive. My attempt to call the function within the link function resulted in an error message saying TypeError: scope.setCurr ...

jQuery Accordian malfunctioning for all elements except the first one in the list

Trying to implement an accordion feature that can be utilized across the entire website. The current logic seems to be partially functional... When I click on any of the accordions, it should open by adding a 'show' class, but this only works for ...

Retrieve the previous value of the selection change with the Mat Select function

In my current project, I have a form with a mat-select dropdown. Whenever the user makes a selection, a dialog pops up to confirm the choice. However, I am facing an issue: The selectionChange() event is triggered when the value changes and provides the n ...

Triggering an Angular AJAX call by selecting a radio button

I am currently working on implementing a CRUD functionality in my app for the admin console. My tech stack includes MongoDB, Spring, Bootstrap, and Angular. The interface consists of a list of radio buttons on the left side containing names of collections ...

Is a Javascript-only application compatible with Amazon S3 cloud storage?

I am currently investigating the validity of the following statement: Based on my research, it seems unlikely to create a web application using only JavaScript - without any server-side logic - hosted on Amazon S3 that can also store data solely on S3 whi ...

Selenium EventFiringWebDriver JavaScript: There is a SyntaxError due to a missing closing parenthesis after an argument in

Attempting to run a javaScript command through the EventFiringWebDriver class in Selenium. EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(driver); eventFiringWebDriver.executeScript("document.querySelector('[ng-reflect-title=&ap ...

How to access the CSS and JS files in the vendor folder using linemanjs

Currently, I am in the process of developing a web application utilizing linemanjs. However, I have encountered an issue where the vendor css and js files are not being referenced correctly when explicitly included. I would appreciate any guidance on what ...

Can the height of one div be determined by the height of another div?

Here's the specific situation I am facing: I want the height of Div2 to adjust based on the content of Div3, and the height of Div3 to adapt based on the content in Div2. The height of Div1 is fixed at 500px. Some of the questions that arise are: I ...

Challenges with handling form elements in JavaScript

I'm currently developing a project and facing challenges in implementing input validation for a form. My goal is to ensure that the form only gets submitted and redirects to a specific URL if all requirements are met. To achieve this, I am utilizing J ...

Alternative method for handling web requests in case JavaScript is not enabled

Issue: i) I am developing a JSF2 application and need to implement a tab control on a page. When a user clicks on a tab, the content for the panel below should be loaded from an xhtml file on the server using an ajax call. ii) I want this functionality ...

Using v-model with the input type files in Vue.js allows for easy two

Is there a way to retrieve data from v-model array in an input type of "file" that allows multiple selections? <input type="file" multiple v-model="modFiles[index]"> <input type="file" multiple v-model="modFiles[index]"> <input type="file" ...

"Obtain a DOM element within an Angular directive by using the jQuery find method

When inspecting the DOM, I can see the element anchor tag present but cannot retrieve it using jquery.find(). The console returns a length of 0, preventing me from initializing angular xeditable on that element. angular.module('built.objects') ...

Click event not functioning in programmatically loaded HTML

I am facing an issue with a JSON file that contains the page content I am trying to load. The link within it appears as follows: <a data-ng-click='foo()'>Bar</a> When I load this page content into the HTML page: <p class="body" ...

What steps do I need to take in order to establish a connection to a GridFS bucket

I have successfully implemented file uploads using a gridfs bucket. However, I am facing challenges with downloading files. For retrieving files, I need to access the bucket instance that I created within the database connection function: const connectDB ...

What is the best way to empty a TextField in a React application?

Greetings to all! I could use some help figuring out how to clear a TextField after clicking the icon. Any suggestions would be greatly appreciated. Thanks! const [filteredLocations, setFilteredLocations] = useState(locations); const clearSearch = () =& ...