The angular.injector() method in the console is failing to return a singleton instance as expected

Below is the script for Angular:

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

app.factory 'MyFactory', ->
  val: 'Clark Kent'

app.controller 'MainCtrl', ($scope, MyFactory) ->
  MyFactory.val = 'Waldo'
  $scope.myFactory = MyFactory

Execute this code in your browser console:

angular.injector(['ng','app']).invoke(function(MyFactory) { console.log(MyFactory); })

Unexpectedly, instead of Waldo, you will see Clark Kent !!

Why is the returned object different?

For more details, visit this plunkr link

Answer №1

Angular services are unique in that they act as singletons, being created only once per injector.

An exception to this rule is the angular.injector function, which generates a new injector every time it is called.

To access the current app's injector, use:

angular.element(domElement).injector()

Here is an example:

angular.element(document.querySelector('html')).injector().invoke(function(MyFactory) { console.log(MyFactory); })

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 retrieve the IP address of a client using Node.js within a setInterval loop

Working on a project utilizing nodejs to fetch client IP Addresses. Within the setinterval function, I have set up the following code: var countdown2 = setInterval(function(){ async function baked(req, res, id){ var getIP = req.headers['x-forward ...

The definitive method for resolving synchronization problems between Protractor and Angular

The Issue at Hand: We recently encountered a common error while attempting to open a specific page in our application during a Protractor end-to-end test: Error: We timed out waiting for asynchronous Angular tasks to complete after 50 seconds. This cou ...

The ConsoleCapture does not capture every console error for Sentry

Running into an issue capturing console errors with Sentry in a Next.js app. The problem arises from an error within a library that is inaccessible to us, specifically related to WebSocket "WebSocket is already in CLOSING or CLOSED state" This error is c ...

Building a dynamic attribute management system with vue and vuetify

In the backend business object, there is a custom attributes data structure that allows clients to add key/value pairs for storing in the database. For instance: Map<String, String> customAttributes; Here's an example of how it would look in th ...

What is the best way to transfer data from a controller to a router in a node.js application

I have a folder structure with two files: a controller and a router. I have successfully pulled data from MongoDB in the controller, but I am having trouble passing it to the router in order to send it to the client using an API. Any ideas on what might be ...

"Exploring error handling and exception management in AngularJs with

I'm debating whether or not using try/catch will have a performance impact on my AngularJs application. Can you point me in the right direction? ...

Is the Angular-fullstack generator production application experiencing issues with serving socket.io correctly?

Having a bit of trouble with two angular-fullstack apps deployed on AWS using the same setup and configuration. It appears that socket.io-client/socket.io.js is not being properly served on one of them, despite both apps having identical settings. There ...

Deactivate multiple input fields by utilizing various radio buttons

I need help with enabling and disabling input fields based on radio button selection. When the first radio button is selected, I want to disable three input fields, when the second is selected, only two specific input fields should be enabled (SHIFT START ...

Is checking for an email address in a form necessary?

I am currently in the process of creating a coming soon page. I have included a form on the page where users can sign up using their email addresses, which are then sent to me via email. However, I need assistance in determining how to verify that the in ...

Does Internet Explorer 10 support the FormData object?

I've developed a JavaScript app that enables me to upload images asynchronously, and it works seamlessly in most browsers. However, the infamous Internet Explorer is causing some trouble... To address this issue, I devised a workaround for IE9- versi ...

Transforming the output from a processor into an array structure

Being a newcomer in the field of development, I have a question about how to retrieve data based on my requirements and what is considered the best practice? This is the structure of my design: JavaScript (Ajax call) >> ashx handler (Access databa ...

I keep running into a problem that says "Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))". I've been unable to come up with a solution so far

const Header = () => { const firebaseAuth = getAuth(app); const provider = new GoogleAuthProvider(); const [{user}, dispatch] = useStateValue(); const login = async () =>{ const { user: { refreshToken, providerData }, } = await sign ...

Capturing screen captures while using Protractor on BrowserStack

Greetings! I am currently in the process of capturing screenshots using protractor and browserstack, and I have the following conf.js file: var HtmlReporter = require('protractor-html-screenshot-reporter'); var reporter=new HtmlReporter({ b ...

What is the process for sending a json response from a function?

Currently, I am experimenting with Javascript, node js, and sails. I am in the process of learning and figuring out how to accomplish certain tasks. At the moment, I have a simple example that I am working on. My goal is to fetch a json using a rest call ...

Selenium WebriverJS does not support right mouse button clicks in PhantomJS

Currently, I am utilizing Selenium in combination with WebdriverJS to automate a straightforward web application. However, an issue arises when transitioning from Chrome to PhantomJS, resulting in the test not functioning as intended. Specifically, the rig ...

An error occured: Unable to access undefined properties (specifically 'hasOwnProperty')

I encountered an issue and managed to solve it. I am currently working on creating an update profile page for my Express app using Mongoose, but I keep getting the error "TypeError: Cannot read properties of undefined (reading 'hasOwnProperty')". ...

Looking for a way to store data in a sub-document in MongoDB? I am having an issue where my farm sub-documents

After many attempts, I am still facing issues while saving farm data for a User. I created an API to sign up a user and save their data, including the farm object. However, every time I try to update the code, the farm object turns into null. The goal is t ...

Tips for creating modular Angular controllers

Feel free to modify the title as needed. I am familiar with writing controllers in a modular manner. var controllers = {}; controllers.ToDoController = function($scope){ //... }; Alternatively, you can achieve the same results using: var app = angul ...

initiate a click event within another click event

This is an HTML Code snippet: <ul id="linkjess"> <li><a href="javascript:setfolder('medewerkers', '1000');">medewerkers 1000</a></li> <li><a href="javascript:setfolder('medewerkers', ...

Execute a function that handles errors

I have a specific element that I would like to display in the event of an error while executing a graphql query (using Apollo's onError): export const ErrorContainer: React.FunctionComponent = () => { console.log('running container') ...