What is preventing the factory from gaining access to the controller?

I have set up a notification factory and passed it inside the controller. However, when I try to assign the factory to the scope within the controller, I am encountering an error.

alertsManager

 MyApp.factory('alertsManager', function() {
                return {
                    alerts: {},
                    addAlert: function(message, type) {
                        this.alerts[type] = this.alerts[type] || [];
                        this.alerts[type].push(message);
                    },
                    clearAlerts: function() {
                        for(var x in this.alerts) {
                            delete this.alerts[x];
                        }
                    }
                };
            });



var LoginController = function($scope, $rootScope, alerts, alertsManager)
{
    $scope.alerts = alertsManager.alerts;
    // encountering error.
    **angular.js:11594 TypeError: Cannot read property 'alerts' of undefined**
}

LoginController.$inject = ['$scope', '$rootScope', 'alerts', 'alertsManager'];


**Why is the factory not accessible inside the controller?*

Answer №1

Consider the code snippet provided below.

code:

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

myApplication.factory('notificationsManager', function() {
  return {
    notifications: {'notification':"I am from the factory service"},
    addNotification: function() { //code },
    clearNotifications: function() { //code }
  }
});

myApplication.controller('MyCtrl',['$scope','notificationsManager', function($scope, notificationsManager) {
  $scope.message = notificationsManager.notifications.notification;
}]);

Note : Remember to Inject the factory service into the Controller

To view a working demo, click here .

Answer №2

There is no requirement to include 'notifications' as a parameter in the controller.

Answer №3

Forgive me for asking a rather foolish question, but have you double-checked to see if these files are actually included in your Index.html file?

It should look something like this:

 <script src="app/services/alertsManager.js"></script>

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

Efficiently update a multi-step form using Ajax and jQuery by adding new content without needing to reload the

Is it possible to create a multistep form on a single page without reloading the div with content from a PHP file, but instead appending it below? Here is my current progress: $(document).on('submit', '#reg-form', function(){ var ln = ...

The function window.open when using the target '_blank' will launch a fresh browser window

I'm attempting to open a link in a new browser tab (not a new window). When I place a link on the page like this: <a href="#" onclick="window.open('http://www.google.com', '_blank');"> Click Here</a> when a user clic ...

Require assistance with understanding the aes-256-cbc encryption using oaepHash

Procedure for Secure Data Encryption: Generate a random 256-bit encryption key (K_s). For each Personally Identifiable Information (PII) value in the payload: 1. Pad the plaintext with PKCS#7 padding. 2. Create a random 128-bit Initialization Vector (IV). ...

When working with an Angular application, IE9 may display the error message: "An internal error occurred in the Microsoft Internet extensions"

My application is encountering an issue in IE9: Error: A Microsoft Internet Extensions internal error has occurred. Error: Access is denied. When using IE's dev tools for debugging, the issue seems to be related to localStorage. if (localStorage) ...

Merge information from various sources using ajax

Currently, I have a single ajax request that retrieves data from an API and uses it to generate a table. Now, I'm looking to modify the code so that it can retrieve data from two different URLs and merge them into the same table (retTable). Below is ...

The jQuery code is failing to affect a form that has been dynamically inserted into the DOM using AJAX

Utilizing jQuery's hover event, my app includes a standard star voting functionality. The logic for star voting was previously rendered with the rest of the page upon the initial DOM load through an HTML request. However, I am interested in relocating ...

Non-responsive Click Event on Dynamically Created Div Class

I am facing some uncertainty in approaching this problem. In the HTML, I have created buttons with additional data attributes. These buttons are assigned a class name of roleBtn. When clicked, they trigger the jQuery function called roleBtnClicked, which ...

Struggling to retrieve an element from an object received through a get request in Express

I am facing an issue with a get request that returns an array of objects retrieved from a database using Knex. I am trying to use .map to make these objects accessible, but I am struggling with accessing the final element which is a sum(). It seems like a ...

What is the best way to remove a specific item from a list of maps in DynamoDB based on a particular attribute value within the

Below is an example of a list I have: { "favorites": [ { "createdAt": 1448998673852, "entityId": "558da3de395b1aee2d6b7d2b", "type": "media" }, { "createdAt": 1448998789252, "entityId": "558da3de395b1aee2d6b7d83 ...

An error occurred during runtime due to a TypeError when trying to execute the 'setItem' function on 'Storage'. The error message indicates that 2 arguments are required for this function, but only 1 argument

Having an issue with the local storage not working and the screen showing up as white in the browser. 5 | const getFromLocalStorage = () => { 6 | if (typeof window !== undefined) { > 7 | const value = localStorage.getItem(& ...

Error encountered when attempting to reinitialize DataTable while iterating through multiple tables and searching within tabs

Currently, I am utilizing DataTable to display 3 separate tables with the help of tabs, along with a search function. However, every time I load the page, I encounter a reinitialization error. Here is the snippet of my code: _datatables.forEa ...

Update the date on the AngularJS datepicker to today's date

When a button on my md-card is clicked, a modal opens up allowing me to select a date. Below is the code for this functionality: <!-- Modal --> <md-dialog aria-label="Date Picker"> <div class="modal-content"> <div c ...

"Developing a JSON object from a Form: A Step-by-

Currently utilizing the Drag n Drop FormBuilder for form creation. My objective is to generate a JSON representation of the form as shown below: { "action":"hello.html", "method":"get", "enctype":"multipart/form-data", "html":[ { ...

Icons are failing to display in the dropdown menu of MUI after an option is selected in ReactJS

There seems to be an issue with the icon in the select tag. Initially, it is not showing which is correct. However, when you click the dropdown, the icon appears as expected. But after selecting an option, if you click the dropdown again, the icon disapp ...

Store the encoded data in a variable

After looking at some examples, I attempted to create my own solution but encountered an issue with the Promise being stuck in a "pending" state. My goal is to store base 64 data into a variable named base64. Can anyone offer guidance on what's wrong ...

A configuration for ".node" files is missing: specifically, the loader for node_modules/fsevents/fsevents.node in a project using Vite

Everything was running smoothly in my Vite + React project until last week when out of nowhere, I encountered this error: No loader is configured for ".node" files: node_modules/fsevents/fsevents.node node_modules/fsevents/fsevents.js:13:23: 1 ...

What makes Angular date pickers sluggish?

Have you ever noticed that Angular JS date pickers consume a lot of CPU? When multiple date pickers are present on a page, they can noticeably reduce the site's speed. Is there a way to minimize this issue? Take for example the official Angular for ...

Adjust the text color of a div element by clicking a button with the help of JavaScript

I am trying to change the font color of my div when a button is clicked using JavaScript. The two buttons I have are 'Green' and 'Red'. <button type="button" class="green">Green</button> <button type="button" class="red" ...

Refreshing data from firebase on each route change

I created an Angular service that retrieves items from Firebase using snapshotChanges and returns them. In my component, I subscribe to the data and store it in an array. I then display the data in cards using ngFor. However, whenever I navigate between p ...

Leverage Angular's constant feature in scenarios that extend beyond the

Even though it may not be recommended, I find it fascinating to use Angular services outside of the angular framework. One example is having .constant('APIprefix','/api') I am curious about how to access the value of APIprefix outside ...