Ways to control the number of function invocations in an AngularJS controller

I am facing a challenge where data is being fetched from multiple controllers, causing functions to hit the server more than fifty times until they receive a response. I am unsure how to handle this situation effectively and would appreciate some guidance.

mainControllers.controller('AddProductController', ['$scope', '$http', '$routeParams', '$cookies', '$rootScope', 'Upload', '$timeout', '$uibModal', '$log', '$document', '$window', 'variantsService', 'toaster', '$route', '$rootScope', 'Lightbox', function ($scope, $http, $routeParams, $cookies, $rootScope, Upload, $timeout, $uibModal, $log, $document, $window, variantsService, toaster, $route, $rootScope, Lightbox) {


    /*Currency dynamic*/
    $scope.currency = function () {
        $http.get('currencies',
                {headers:
                            {'Content-Type': 'application/x-www-form-urlencoded',
                                'Authorization': $rootScope.keyword_auth_token, 'Accept-Language': $cookies.get('type')}
                })
                .success(function (data) {
                    $scope.user_curr = data[0].code;
                })
                .error(function (data) {
                    console.log(data);
                });
    };

    /*Currency dynamic ends here*/
    $scope.currency();

}]);

Is there a way to limit the number of hits on the server in this scenario?

Answer №1

It's not ideal to have multiple controllers for one partial. It's recommended to utilize angular factories to handle data in such scenarios. To simplify, you can remove the line $scope.currency(); from your controller (as it will trigger an api call upon initialization) and instead use ng-init built-in directive. In your partial with ng-controller="AddProductController", include ng-init="currency()" if you need to make an api call.

Answer №2

To ensure full control over calls, I always incorporate them into a service. Here is an example of how you can do this:

app.service("currencyService", function($q, $http) {
    var _currencyPromise = null,
        _currencies = null;

    this.getCurrencies = function() {
        var deferred = $q.defer();

        if (_currencies) {
            deferred.resolve(_currencies);
        } else if (_currencyPromise) {
            _currencyPromise.then(function(response) {
                deferred.resolve(response.data);
            });
        } else {
            _currencyPromise = $http.get("..");
            _currencyPromise.then(function(response) {
                _currencies = response.data;
                deferred.resolve(_currencies);
            }, function(error) {
                _currencyPromise = null;
                deferred.reject();
            });
        }

        return deferred.promise;
    }
});

In your controllers, you can utilize this service to make the http call only once:

app.controller("myCtrl", ["$scope", "currencyService", function($scope, currencyService) {
    currencyService.getCurrencies().then(function(currencies) {
        $scope.user_curr = currencies[0].code;
    });
}]);

For further reference, please check out this jsfiddle. You will notice that the API is called only once in the console.

Answer №3

My solution is straightforward. Let's say I have a view structured as follows:

<div ng-controller="HomeController">
<div class="active tab-pane" ng-controller="AddProductController" ng-init="subcategories_id();currency();">

<p>{{user_curr}}</p>

</div><!--ends here->
<p>first controller {{abc}}</p>
</div>

I am utilizing the nginit attribute and it functions perfectly.

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

PhantomJs is only providing partial responses

I have been attempting to retrieve a response from the following URL using PhantomJS:- https://www.trivago.com/api/v1/bin/accommodation/2891353/deals?iPathId=34812&iRoomType=1&aRooms=&aDateRange%5Barr%5D=2017-05-24&aDateRange%5Bdep%5D=2017 ...

JavaScript: Reorder an array to alternate between largest and smallest elements, starting with the largest

When working with an array of integers that need to be sorted in a specific order, such as: [1, -1, -3, 9, -2, -5, 4, 8,] We must rearrange them so that the largest number is followed by the smallest number, then the second largest number followed by the ...

javascript href clears Internet Explorer webpage

I noticed a strange issue with my HTML page. In Internet Explorer, when I click on the link, it displays the return value on a blank page. However, in Chrome, it simply executes the function without affecting the page appearance. Is there a way to make I ...

Using Moment.js to showcase historical information within a specified timeframe based on the user's timezone

I'm finding it challenging to properly handle historical data display: Current Situation: The database contains records stored in "YYYY-MM-DD HH:mm:ss" format in UTC+0 (MariaDB - DateTime type) A web application (using moment.js) allows users to se ...

Personalize Drop-Down Selection

Currently implementing bootstrap on a site and seeking to enhance the dropdown menu customization. The default navbar appearance is present, with dropdown elements appearing upon hover. My goal is to include an icon next to each item in the navbar and ha ...

Serve as a proxy for several hosts with identical URL structures

I've been utilizing the http-proxy-middleware to handle my API calls. Is there a way to proxy multiple target hosts? I've searched for solutions in the issues but still haven't found a clear answer. https://github.com/chimurai/http-proxy-m ...

Encountering a Next.js installation error due to the inability to locate the module fs

Having trouble with the installation of a new Next.js 14 app. I've searched on Google and Stack Overflow but haven't been able to find a solution. I'm stuck at this point. Can anyone offer some assistance? What I have attempted: npx creat ...

Issue with Material-UI DataGrid Component: Unable to access property 'length' as it is undefined

I need to display my JavaScript Object Data in a table format with pagination and sorting capabilities. I have chosen the DataGrid component from Material UI, but I am encountering some errors. Below is the code snippet: import React from 'react&apos ...

Embed a javascript tag to print a PDF document

I have been struggling with printing a PDF file using JavaScript. I attempted to use the embed trick suggested in this Silent print a embedded PDF but unfortunately, the print function remained undefined. Then, I tried another approach using an Iframe and ...

Modify a dropdown menu selection and process it using ajax technology

My Simple HTML Form: <select id="single"> <option>Option 1</option> <option>Option 2</option> </select> <input value="load()" id="test" type="submit" /> <div id="result"></div> Javascript Co ...

Click on a Marker to automatically zoom to its location using Leaflet mapping technology

I have successfully implemented a feature to display markers on the map from a geojson file. Currently, when I hover over a marker, I can see its properties in a popup. However, I now want to enhance this functionality so that when a user clicks on a mar ...

How can I retrieve the value of a JavaScript variable using Ajax?

Hello everyone! I've been a long-time user of various programming forums, but this is my first time posting. Lately, I created a really simple browser-based game, and when I say simple, I mean it's incredibly basic. The whole game logic resides ...

Concealing UI elements within the primary stack during navigation to a nested stack in React navigation

Is there a way to hide the user interface in my main stack when I switch to the nested drawer stack? I am currently facing an issue where the header from my main stack appears above the header in my nested stack when I navigate to a screen using: navigat ...

Transferring HTML variables to an Angular Component

I am currently trying to transfer the information inputted into a text-box field on my webpage to variables within the component file. These variables will then be utilized in the service file, which includes a function connected to the POST request I exec ...

``What are the steps to identify and retrieve variables from an Angular HTML template by utilizing Abstract Syntax Trees

I am currently working on a project in Angular that utilizes HTML and Typescript. My goal is to extract all the variables from the HTML templates of each component. For example, let's say I have an HTML component like this: <div *ngIf="value ...

Strategies for Synchronizing Multiple Asynchronous Calls in NodeJS

I have a function getAliasesByRoleDetailed(role) that is responsible for retrieving user data based on a given role. This particular function utilizes axios to fetch the necessary data. The result obtained from executing this function appears in the follo ...

Error handling middleware delivering a response promptly

Issue with my express application: Even after reaching the error middleware, the second middleware function is still being executed after res.json. As per the documentation: The response object (res) methods mentioned below can send a response to the cl ...

Does the method in the superclass "not exist" within this type....?

Our TS application utilizes a JavaScript library, for which we crafted a .d.ts file to integrate it with TypeScript. Initially, the file resided in a "typings" directory within the project and everything operated smoothly. Subsequently, we opted to relocat ...

What is the best way to group/merge multiple objects that have the same name into a single object (Nesting)?

I have a dataset containing students' names and their marks in different subjects stored as an array of objects. My goal is to merge the data into a single object for each student with matching names, resulting in one record per student. Here is an ex ...

Incorporating JavaScript and Alpine.js to Monitor and Log Changes in Input Range Values

I have developed a basic app that logs the input range value to the console when the range input changes. Interestingly, it works flawlessly when I slide the slider left and right with my cursor. However, when I programmatically change the value using Ja ...