Differences between Angular's $injector and Angular's dependency injectionAngular

As a newcomer to Angular, I am exploring the use of $injector and its get function to retrieve specific services. For instance:

app.factory('$myService', function($injector) {
   return { ...
            var http = $injector.get('$http');
            ....
   }
}

This code snippet shows how to assign the Angular $http service to the variable http.

In some other examples, I have encountered syntax like this:

app.factory('$myService', function($http) {
    return {...}

Here, the $http service is injected directly into the factory.

Are there any differences between these two approaches? When would be the appropriate time to use one over the other?

Thanks in advance!

Answer №1

Do you think it's the same or do you have a preference?

In my view, directly injecting your dependencies (such as $http) is more beneficial for readability.


Keep in mind that you also have the option to utilize the $inject annotation:

someModule.controller('MyController', MyController);
MyController.$inject = ['$http'];

var MyController = function($http) {
    // ...
}

Answer №2

Although they serve similar purposes, the way in which you utilize them varies. When working with a controller where the requirements are known in advance, it is generally preferable to use parameter-based injection:

var controller = ['$http', function($http){ /* Controller stuff here */ }];

However, in more complex scenarios where all dependencies may not be known (such as creating a sub-framework that allows users to specify dependencies), it may be necessary to programmatically inject dependencies using $injector:

var controller = ['$scope','$injector', function($scope, $injector){
    $scope.dependencies = [];
    $scope.injectFromString = function(dependency){
        $scope.dependencies.push($injector.get(dependency));
    };
}];`

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

Display visual information without requiring the parameters to be filtered beforehand in vue.js

Upon opening my page, I encountered an issue where the graphics appear blank. This is because I set up the callback for generating graphic data through params request. I wish to first fetch the general data when the page opens, and only load with params w ...

What is the best way to send props to a styled component without needing to convert them to transient props beforehand

Recently, I designed a custom Text component that accepts several props. These props are then forwarded to the styled component where specific styles are applied. However, I am facing an issue where I do not want these props to be passed down to the DOM, b ...

When data is stored in Internet Explorer's cache, any changes made are not being reflected in

Internet Explorer stores data in cache and even if there are changes, it may not reflect onclick. However, when I open the developer mode and try to access the same, then it works perfectly. This issue only seems to occur in IE as all other browsers work f ...

Tips for extracting the two characters following a space in a string with or without the use of regex

How can I extract only the initials of 2 characters after spaces? See the code snippet below: const name = "John Peter Don"; const result = name.match(/\b(\w)/g).join(''); console.log(result)// JPD->> i want only JP ...

Can Node.js be utilized to generate an XLS excel file while specifying the cell type?

I've noticed that many libraries have the capability to export to XLSX (Excel > 2007) or CSV formats, but not in XLS (which I assume is due to its outdated file format). I came across something where if you use fs.createOutputStream("filename. ...

Retrieve JSON data from PHP using D3.request

Looking to extract data from an SQL database using PHP and then convert it into JSON format with the "echo json_encode($array);" function. I have a requirement to create a graph using D3.js, which means I need to transfer this JSON data from PHP. Can anyo ...

Resolve the route expression before the API request is fully processed

As a hobby coder, I have some gaps in my knowledge and despite trying various solutions, I have not been able to solve this issue. Idea Outcome My goal is to call my Express server, retrieve data from an external API, and render the data once it's f ...

Tips on boosting the speed and user-friendliness of your AJAX/REST application

Exploring the Essential Requirements of an Application I am currently developing a comprehensive application using AngularJS (but it could be any framework). This application interacts with a server built on Google App Engine through REST technology. Th ...

Delay the occurrence of a hover effect until the previous effect has finished executing

As I hover over an element, the desired animation is displayed while hiding other elements on the page. The challenge I'm encountering is that if I quickly hover over many divs, the animations queue up and hide the divs sequentially. I want only one ...

Providing input to a nested mongoose query

I can't figure out why I keep experiencing 504 Gateway timeouts. app.get("/api/exercise/log", function(req,res) { let userId = req.query.userId; let from = req.query.from; let to = req.query.to; let limit = req.query.limit; console.log("lim ...

Does React have an event component that detects when a user is actively viewing a specific component, such as a post?

Is there a special React event that fires when the user's gaze is focused on a component? Something like ComponentEnteredShowArea? For instance, videos in Facebook posts play automatically when I direct my attention towards them. It would be ideal i ...

Tips for showcasing elements individually in JavaScript when a button is clicked and halting on a random element

I have some names stored in h3 tags. I want to highlight one name at a time when I click a button, stopping at a random name. <div class="all-names"> <h3 class="name-one"><span class="line">Name ...

Ways to eliminate all attributes and their corresponding values within HTML tags

Hey there, I'm trying to strip away all the attribute values and styles from a tag in html Here's my Input: <div id="content"> <span id="span" data-span="a" aria-describedby="span">span</span> <p class="a b c" style=" ...

What is the best method for converting IDs into objects within ng-options in Angular?

Is there a way to dynamically use an array of IDs as the source of my ng-option directive inside of select? Instead of creating an array of objects with corresponding IDs, I am wondering if there is a method to set a function as the source of ng-option. ...

Incorporating the non-typescript npm package "pondjs" into Meteor applications using typescript files

Implementing the Pondjs library into my project seemed straightforward at first: meteor npm install --save pondjs However, I'm encountering difficulties when trying to integrate it with my Typescript files. The documentation suggests: In order ...

Passing arguments to EJS view with Express

As a newcomer to Node.js/Express/EJS, I've made an interesting observation. I've realized that if I pass arguments from an Express request handler to an EJS view without specifying the argument name, it automatically assigns a name based on the v ...

"The error message appeared stating that the AngularJS Protractor element cannot be clicked at its current position due to another element

Hey there, I've been working on a simple AngularJS application and running into some trouble with Protractor in Chrome. Here's a snippet of my code: HTML: <div> <div> <ul...... <li.........../li> <li............./li> ...

What is the best way to create a Div element that functions as a button, becoming active when clicked while deactivating all other Div elements

function toggleButton1() { $("#button1").toggleClass("button-active button-inactive"); $("#button2").toggleClass("button-inactive button-active"); $("#button3").toggleClass("button-inactive button-active"); } function toggleButton2() { $("#butto ...

Highchart displays text centrally on legend hover

I am struggling with the code provided here. My goal is to make text appear in the center of the donut chart when hovering over the legend. Similar to how it works when hovering over a single piece of the donut chart. var chart = new Highcharts.Chart ...

Selectize Fails to Populate Options Using Ajax

ExpressJS is the platform I am using to develop a management dashboard for a community project. Right now, my main concern is integrating a modal that allows users to add new games to a database. Although I am able to fetch data remotely, I am facing diffi ...