Stopping the recursive function call in AngularJS

Utilizing the following function to retrieve users from a REST API, paginated by offset. Upon successful callback, the function recursively calls itself with a new offset to fetch the next set of users.

Issue: When I change or exit the view, the FetchAttendee-Function continues running until all users are fetched. However, for better performance, I want to halt the process of fetching users.

fetchAttendees(event_id, offset);

function fetchAttendees(event_id, offset) {
    AttendeeFactory(offset).show({id: event_id}, 
        function success(response) {
            [ DO SOMETHING WITH RESPONSE ]
            fetchAttendees(event_id, offset);
        }, 
        function (error) {
        });
}

Therefore, is it feasible to prevent the fetchAttendee-Function from being called when leaving the view Event?

$scope.$on("$ionicView.leave", function(scopes, states) {
    [ ...] 
});

AttendeeFactory

.factory('AttendeeFactory', function ($resource) {
    return function (offset) {
        return $resource('http://10.0.0.6:8000/backend/attendees/:id/', {}, {
            show: { method: 'GET', headers: {'attendee-offset': offset}, isArray: true }
        });
    };
})

Answer №1

Below is a rough pseudo-code structure (not tested for your specific requirements)

// Controller implementation
app.controller('YourController', ['$scope', 'AttendeeFactory', function($scope, AttendeeFactory) {

    ...
    AttendeeFactory.fetchAttendees(event_id, offset);
    ...

}]);

// Listener for state change to pause attendee fetch
AttendeeFactory.pause();

// Service/Factor definition
app.factory('AttendeeFactory', function($resource) {
    var isPaused = true; 

    function fetchAttendees(event_id, offset) {
        isPaused = false;
        fetchAttendeesRecursive(event_id, offset);
    }

    function fetchAttendeesRecursive(event_id, offset) {
        if (!isPaused) {
            Attendee(offset).show(
                {id: event_id}, 
                function success(response) {
                    [ HANDLE RESPONSE HERE ]
                    fetchAttendees(event_id, offset);
                }, 
                function error() {}
           );
        }
    }

    function Attendee(offset) {
        return $resource(
            'http://10.0.0.6:8000/backend/attendees/:id/',
            {},
            {
                show: {
                    method: 'GET', 
                    headers: {'attendee-offset': offset}, 
                    isArray: true
                }
            }
        );
    }

    function pause() { isPaused = true; }

    return {
        fetchAttendees: fetchAttendees,
        pause: pause
    };
});

If the [HANDLE RESPONSE HERE] involves updating the view's scope, additional logic is needed to notify the controller of data changes.

You can utilize $rootScope, $on, and $emit to trigger a message from the service upon attendee fetch for the controller to listen and update accordingly. Here's a basic example:

// in the controller
$rootScope.$on("AttendeeFetchedEvent", function($event, data){
  // handle data updates here
});

// in the factory/service
$scope.$emit("AttendeeFetchedEvent", dataToSendToController);

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

Animating an image inside a bordered div

I'm attempting to create an animated effect where an image moves randomly within the boundaries of a div container. While I've come across solutions for animating within borders, none have specifically addressed keeping the image inside the div. ...

Choose an element based on its position in the index (multiple elements with the same class)

Can you use Javascript or jQuery to select an element by its index? For example: <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> If I have 4 elements with ...

ng-show not syncing with ng-repeat updates

When a language is selected, two lists of data are displayed based on that language. However, there is an issue with the ng-show directive not updating properly when the language is changed. I have already attempted to use $scope.apply() but it has not re ...

How do I implement the use of "lengthMenu: [10, 25, 50]," within an if/else statement effectively?

Could someone help me with defining 2 different configuration lines for a datatable using if-else statements? I've tried writing the code but it doesn't seem to be working as expected. if(role === 1) { lengthMenu: [10, 25, 50], } else ...

Vue Subroutes within nested components do not automatically load

My application features a sidebar that I want to utilize to load the Patient view by default when accessing patient/:id. This should also trigger the loading of the PatientDashboard sub-view. Within the Patient view component, there is a router-view that ...

Submitting an HTML form to trigger a PHP function through AJAX

I am currently working on a task that involves POSTing an email address entered in an HTML form to a PHP script for storage in a database. The script should also handle error messages if the user inputs an invalid email address. I want to make this process ...

AngularJS custom directive with isolated scope and controller binding

I am looking to create a directive that includes both scope parameters and ng-controller. Here is the desired structure for this directive: <csm-dir name="scopeParam" ng-controller="RegisteredController"> <!-- Content goes here--> {{na ...

Attempting to use insertAdjacentHTML on a null property results in an error

I keep encountering the same error repeatedly... Can someone please explain what's going wrong here and provide a hint? Error script.js:20 Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null at renderHTML (script.js:20) a ...

Executing search bar capability through the use of AJAX and HTTP requests in JavaScript

I am currently working on implementing a search feature that will locate data based on the user's query. Specifically, I want to create a search bar in my HTML that can search for book titles stored in my database accessible through GET requests. Alth ...

Utilizing objects from a JSON file within an HTML document

I'm currently in the process of creating a comprehensive to-do list, and I want to establish a JSON file that will link all the items on the list together. Despite my efforts, I find myself uncertain about the exact steps I need to take and the speci ...

Angular Autocomplete directive - retrieve the list of matching items

I am looking to display the first element suggested by the Angular Typeahead directly in the input box, instead of just in the dropdown. I have searched extensively but have not been able to find a way to access the elements shown in the dropdown. The goal ...

Securing a fixed path in Express and Nodejs: Best practices

Using the latest versions of Node and Express, I have organized my project into two folders: public and secured. I want to restrict access to the secured folder to only authenticated users. I have implemented a custom login system, but now I am unsure of ...

Struggling with the nodejs peepcode tutorial - need some help getting it to run

After purchasing and following the latest nodejs peepcode tutorial, I have hit a roadblock at the initial step. I have spent hours trying to debug my code, but tracing errors in nodejs seems like solving a riddle to me. My app structure is as follows: e ...

Navigating with Nokia Here maps: plotting a path using GPS coordinates

I am currently developing a GPS tracking system and my goal is to visually represent the device's locations as a route. The challenge I'm facing is that there is a REST API available for this purpose, but my client-side application relies on soc ...

Placing an icon to the left of the primaryText within the <ListItem> component of Material UI

Seeking to enhance a <ListItem> from React Material UI that currently displays a checkbox on the left side. My goal is to insert an image or icon between the checkbox and the title, positioned to the left of the title. Upon reviewing the documentatio ...

Issues arise when Typescript's declaration merging feature does not function correctly when utilizing ts-node

I am currently working on a project that involves using the express-session package. My goal is to modify the session object by adding a user key. req.session.user = 123; After reading through the accepted answer in this question, I learned about declarat ...

Singling out a particular navigation tab

When attempting to link specific table IDs so that the corresponding tab is active when opened (i.e. www.gohome.com/html#profile), I am facing an issue where the active tab remains unchanged. Even after specifically calling out tab IDs, there seems to be n ...

FixPermissions not working properly | Discord.js EXPERT

I am currently in the process of updating my bot to be compatible with the latest version of discord.js. I have successfully made various changes, but I am facing an issue with the overwritePermissions section within my ticket command. For some reason, the ...

Nesting placeholders is not permitted in i18n

I am attempting to implement Interpolation with Vue3 and vue-i18n version 9.3. However, when I try to pass arguments, I encounter the following error: Message compilation error: Not allowed nest placeholder 1 | Showing {{from}} to {{to}} of {{total}} ent ...

Having trouble with Javascript? Your page unexpectedly resets

Hey there, I'm facing a confusing issue. I created a registration page for a project, and every time I enter the information, it should be stored in a cookie. After entering the information for the first time, I saw it in the bar, but it wasn't p ...