What is the problem with the dependencies in this factory?

I am currently utilizing AngularJS and I am looking to retrieve a controller using one factory that is dependent on another.

This can be illustrated as follows:

MyCtrl -> Factory1 -> Factory2 

I attempted to achieve this in three separate files (loaded in the following order):

Factory2.js

app.factory('Factory2', function () { ... })

Factory1.js

app.factory('Factory1',['Factory2', function (Factory2) { ... })

controller.js

app.controller('MyCtrl',['$scope', 'Factory1', function ($scope, Factory1) { ... })

Within my HTML code, I have included:

<script src="services/factory2.js" type="text/javascript"></script>  
<script src="services/factory1.js" type="text/javascript"></script>
<script src="controllers/controller.js" type="text/javascript"></script>

Despite these efforts, I encountered an error:

Unknown provider: Factory2Provider <- Factory2 <- Factory1

What could be causing this issue? Am I overlooking something in my code?

Answer №1

Optimizing your code by utilizing modules can eliminate the need for $inject

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

angular.module('factories', [])
    .factory('Factory2', function () { })
    .factory('Factory1', ['Factory2', function (Factory2) {
         return myCustomFunction = function () {
             alert('todo');
         }
    }]);

angular.module('mymodule', [])
    .controller('MyCtrl', ['$scope', 'Factory1', function ($scope, Factory1) {
    $scope.text = "testing";
}])

http://jsfiddle.net/kL78rdr3/3/

Answer №2

Have you considered utilizing explicit injection using $inject? This method provides a higher level of control over the dependencies in your code. Here is an example to illustrate this:

profileController.js

function profileController (service, params, dataProvider) {
    //implementation
}
profileController.$inject = ['$scope', '$routeParams', 'dataProvider'];
app.controller("profileController", profileController);

dataProvider.js

var dataProvider = function (http, logger) {
    //implementation
}
dataProvider.$inject = ["$http", "$log"];
app.factory("dataProvider", dataProvider);

Check out this resource for more insight: Explicit Dependency Injection

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

Is it possible to trim a video using HTML code?

I am trying to find a way to crop a video using HTML 5. <video id="glass" width="640" height="360" autoplay> <source src="invisible-glass-fill.mp4" type="video/mp4"> </video> Currently, the video has a resolution of 640x360. However ...

Loading a previously saved Sortable in Angular UI

I have a tabset that can be sorted, and it works as expected. However, I would like the user's tab order to be saved and not lost when they refresh the page. <uib-tabset ui-sortable="sortableOptions" class="tab-container" my-restrict access="st ...

Showcasing information from a database on an HTML page with the use of Node

I am currently attempting to fetch data from my database and display it on an HTML page in a table using EJS for rendering. I found inspiration for my code on this website: Although the database connection is successful, I am encountering difficulties wit ...

Using a JavaScript script in my HTML alongside Vue.js is not possible

Hello there! I recently created a Node.js server and now I'm trying to display an HTML file that contains a Vue script which loads data using another method written in a separate JS file. However, when I attempt to load my HTML file in the browser, ...

Eradicating a character from an Object using Jquery/Javascript

Looking at this code snippet, it appears that the 3rd column is not calculating correctly due to a comma being present in one of the values. Is there a way to rectify this issue without directly removing the comma? I am aware that using .replace(/,/g,&apos ...

Ways to Display or Conceal content based on id when the checkbox is selected

I'm facing a challenge and I need help understanding how to display data based on their id when a checkbox is checked. For instance, when the first checkbox is ticked, I only want the address labeled "0" to be visible while hiding all other addresses ...

Modify a Google Docs script for use in Google Sheets

I created a function called "myFunk()" that works flawlessly in Google Docs. It essentially looks for fields marked with ## in a sheet and replaces them with user input. However, when I attempt to run it in Sheets after making some changes to the functions ...

Async function is improperly updating the array state by overwriting it completely instead of just updating one item as

I am working on a file upload feature where each uploaded file should have a progress bar that updates as the file gets uploaded. I'm using a state to keep track of selected files and their respective progress: interface IFiles { file: File; c ...

Identify the element in which the JS function was executed (excluding the use of IDs)

Take a look at this line: <div onload='loadContent();'></div> Here's the JavaScript function I have: function loadContent() { $.ajax({ url: '/ContentController.php', success: function(data) { //update t ...

The identifier 'name' is not found in the specified data type

How can I resolve the error 'Property 'name' does not exist on type' in TypeScript? Here is the code block : **Environment.prod.ts** export const environment = { production: true, name:"(Production)", apiUrl: 'https://tes ...

I am looking to send a combination of string and HTML data to the controller when using the Summernote editor in MVC

As a beginner in MVC development, there are certain aspects that I am still struggling with. Currently, I am using the Summernote Editor to compose blog posts and Ajax to submit them. However, I encountered an issue when trying to send both HTML data from ...

One Directive can contain a multitude of methods that each return a different

Creating a base template for my web application involves using just One Directive with Multiple Methods that return different templates. I approached this task similarly to how I handle calling Services. SERVICE app.service('myService', fun ...

The jQuery function throws an Error that is not caught by the surrounding try / catch block

Recently, I've been enhancing error handling in my JavaScript objects that heavily utilize jQuery. However, I've run into an issue where throwing a new Error from within a jQuery method is not caught by the surrounding catch statement. Instead, i ...

Triggering a Dialogflow Chat Window with a click on a Material-UI Floating Action Button in a ReactJS application

I have encountered an issue in my code where I am attempting to toggle the display of a Dialogflow Chat Window, <ChatWidget />, when a user clicks on the Material-UI Floating Action Button, <FloatingActionButton/>. The default state is set to f ...

Failed to set CSS variable in Electron

My current dilemma involves CSS variables not being properly set. I am utilizing electron and attempting to establish them in this manner: for (let Button of ThemeButtons){ Button.addEventListener("click", e =>{ let Color = Button.s ...

Using AngularFire: How can you connect and bind data to the $scope efficiently?

Currently delving into the world of Firebase and noticing the differences between it and MongoDB. ...

Most effective method for requesting data from the server

I am working on an Ionic application that requires integration with a backend system. One of the functionalities I need to implement is user login, followed by retrieving various user details such as name, email, height, etc. These values will be used in ...

Is there a way to automatically calculate the sum of two boxes and display the result in a separate

I am working with two boxes: one is called AuthorizedAmount and the other is called LessLaborToDate: <div class="col-md-6"> <div class="form-group"> <label>Authorized Amount</label> <div class="input-group"> & ...

Clicking the button to send the form using JavaScript

Currently, I am dealing with a shopping cart plugin that relies on a basic form on the product page to send values such as price and product name. However, I am facing an issue where this plugin uses a standard submit button to transmit the values, and I w ...

Using discord.js within an HTML environment can add a whole new level of

I'm in the process of creating a dashboard for discord.js, however, I am facing difficulties using the discord.js library and connecting it to the client. Below is my JavaScript code (The project utilizes node.js with express for sending an HTML file ...