Angular calls a factory method from within its own factory

When working in my controller, I encountered a situation where I needed to call a factory function recursively. Previously, the code worked fine as simple JavaScript functions not defined within the factory itself, but I wanted to improve isolation.

Here is an excerpt of the code from the controller:

myApp.controller('VisionCtrl', ['$scope', 'AppFactory', function ($scope, AppFactory,) {
    var promiseTaxo;
    promiseTaxo = AppFactory.getTaxonomy("vision3", "Vision Type");
}])

And in the factory module:

myApp.factory('AppFactory', ['$http', '$q', function($http, $q, TaxoFactory) {
    return {
        getTaxonomy: function(group, termSet) {
            ... lots of code ....
            if (termSet.length > 0) { getTaxonomy(group, childTermSet) }
        }
    }
}])

This example is somewhat simplified, but essentially, the getTaxonomy function will recursively call itself when encountering children nodes. While handling asynchronous processing and promises, everything works smoothly when this code is placed outside the factory.

The challenge I'm facing now is figuring out how to properly invoke getTaxonomy inside getTaxonomy!

Answer №1

To access the taxonomy, you have two options: you can follow @elclanrs' suggestion and use this.getTaxonomy(), or you can modify your factory to make the call from within:

myApp.factory('AppFactory', ['$http', '$q', function($http, $q, TaxoFactory) {

    var AppFactory = {
        getTaxonomy: function(group, termSet) {
            ... a lot of code here ....
            if (termSet.length > 0) { AppFactory.getTaxonomy(group, childTermSet) }
        }
    }

    return AppFactory;
}]);

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

Issue with Ajax not sending query string to ASP.NET controller

I am currently working with an Ajax function that serializes data sent from my view into a query string. Here is the code snippet: UpdateFIConfig: function ($appForm) { var valid = $appForm.valid(); //if not valid the validate plugin will take ca ...

Error during minification process for file opentok.js at line 1310: react-scripts build

I encountered an error while trying to minify the code in my React project using npm run build. The snippet below seems to be the cause of the issue. Any suggestions on how I can resolve this problem? const createLogger = memoize(namespace => { /** ...

The code functions perfectly on my local machine, however it is not cooperating on the HostGator server

A selection box based on values should appear in text fields, The current code is functional in local host but not working on the hostgator server For example, displaying country options based on the selected state and districts based on the selected sta ...

SharePoint 2013 only allows the first AJAX request to work successfully, except when in Edit Mode

I am facing a challenge of making two AJAX requests simultaneously on a SharePoint page. One request originates from the current site, while the other comes from a team site. When I use different URLs (/events) and (/travel), each one works fine when use ...

Implementing pagination and filtering in a single MERN controller

Is it possible to implement pagination and filtering in the same controller? Filter service:- const filterPosts = async (filterData, token) => { const config = { headers: { Authorization: `Bearer ${token}`, }, data: { ...

Received an unexpected character '?' in NextJS

After setting up a fresh installation of Ubuntu 22.04.1 LTS and installing npm and docker, I encountered an issue while trying to start my NextJS web server with the command npm run dev. An error message appeared as follows: niklas@srv-code01:~/Desktop/Co ...

When collapsing an accordion, Bootstrap radio buttons fail to properly select

I have attempted various methods to achieve the desired functionality of having the accordion content close and open accordingly when checking a radio button, while also having the button visually appear as 'checked'. For a more in-depth example, ...

JavaScript errors due to miscalculations Incorrect calculations lead

Here is the formula I am using in my Javascript code: total = parseFloat(unit * rate) + parseFloat(rateamount) + parseFloat(((unit * rate) + (rateamount)) * (tax/100)); The values for the variables are as follows: unit = 5, ra ...

I'm unsure of the most efficient way to condense this statement

$(document).ready(function(){ if ($(window).width() <961){ $('.item').on('click',function(){ /*---do something---*/ }) }else{ $('.item').on('click',function(){ ...

When NuxtImg is utilized, the image will rotate 90 degrees with Nuxt3 NuxtImg

Recently, I have encountered an issue when using NuxtImg where my images appear rotated by 90°. This problem specifically arises with vertical mobile images that are read from supabase and displayed. Interestingly, the images look fine before uploading th ...

"There seems to be an issue with the compatibility of nginx:alpine configuration when using it

I want to try hosting my angular app in my local browser. This is the configuration in my docker file:- FROM node:10.13.0-alpine as builder WORKDIR /usr/src/app COPY package.json package-lock.json ./ RUN npm cache clean --force COPY . ./ RUN npm install ...

Retrieving properties from a selector's output function

My situation is similar to the scenario described in the accessing react props in selectors documentation. However, in my case, let's assume that the visibilityFilter is coming from the props. Is there a way to achieve something like the following? e ...

"Encountering a challenge when trying to fetch the value of an undefined or null

When it comes to validating the delivery date entered, I have implemented the following code to ensure it is not earlier than the current date... I have utilized custom validation using jQuery... Here is my model: [UIHint("Date")] [DeliveryDateC ...

What is causing the geolocation heading to remain "null" on Android devices when using Chrome?

Recently, I developed a compact geolocation watch using the following code snippet: navigator.geolocation.watchPosition( this.updateLocation.bind(this), this.errorLocation.bind(this), {enableHighAccuracy: true} ); The function updateLocation ...

Update the jQuery script tag with new content - rewrite everything

I am facing an issue with jquery. I need to change the link to src only when "document.write" is present. Below is my code: myscript.js document.write("TEST ABCD"); test.html <html> <body> <button id="example">click me</button&g ...

The code is slicing data, but the changes are not reflecting in the user interface

Initially, there are three drop down menus displayed. Upon selecting an option from the first drop down menu, the values in the second drop down menu load. After selecting an option from the second drop down menu, a new set of drop downs appears. However, ...

Bootstrap Modal closing problem

While working on a bootstrap modal, I encountered an issue where the modal contains two buttons - one for printing the content and another for closing the modal. Here is the code snippet for the modal in my aspx page: <div class="modal fade" id="myMod ...

Updating the title with respect to the current route in AngularJS 1

Is it possible to dynamically change the title displayed in a header based on the current route provided by the router, even when outside of the controller scope? For example, I have a mainMenu controller that is loaded when a specific route is called. The ...

Using node.js to send custom data over a websocket

I came across an excellent tutorial on websockets. In this tutorial, the server decodes and writes a message to the console whenever it receives a message from the client. After that, the server sends the message back to the client. var firstByte = data ...

Handling scroll events in a functional component using React

I'm having trouble understanding why the onScroll function isn't triggering the console.log statement. <table className="table" onScroll={()=>{console.log("Works")}> The console.log just doesn't seem to be exec ...