Removing objects in AngularJS in a synchronous manner

Is there a more efficient way to delete items in a for loop when closing a Bootstrap modal? Currently, I am using a 3-second delay on modal close so that the delete can happen in the background, but this is not ideal. How can I ensure that the modal only closes when all items are successfully deleted? Should I make the delete synchronous or use promises?

$scope.idList = [1, 2, 3];
$scope.deleteItems = function(deleteList){
    angular.forEach( deleteList, function(item) {
        DeleteAPI.remove({itemId: item}, {}, $scope.delSuccess, $scope.delError);
    });
}
$scope.close = function(){
    var pmodal = $modal.open( {
            templateUrl: 'route/pmodal.html',
            controller: 'DeleteCtrl'
        } );
        pmodal.result.then(
            function(check) {}, 
            function(check) {
                if ( check=='proceed' ) {
                    $scope.deleteItems( $scope.idList );
                    $timeout( function() {
                        $modalInstance.dismiss('cancel');
                    }, 3000);
                }
            },
            function(check) {}
        );

}

Answer №1

To ensure synchronous execution in JavaScript, you have the option to either utilize $q.all or manually keep track of responses:

var successCount = 0;
var failureCount = 0;

function checkCompletion() {
    if (successCount + failureCount === deleteList.length) {
        if (failureCount > 0) {
            // handle failures
        } else {
            $modalInstance.dismiss('cancel');
        }
    }
}

angular.forEach(deleteList, function(item) {
    DeleteAPI.remove({ itemId: item }, {}, function() {
        successCount++;
        checkCompletion();
    }, function() {
        failureCount++;
        checkCompletion();
    });
});

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

JavaScript conflicts will arise due to the introduction of Yammer Embed on September 30th, 2014

Is anyone else encountering problems with Yammer embed causing JavaScript errors today? Our various applications across different technologies (SharePoint, IBM, etc) have been functioning normally for months, but this morning we are suddenly seeing a sig ...

Endless loading with Restangular

Currently, I am using a Restangular collection which is functioning perfectly: $scope.threads = Restangular.all('thread').getList({ limit: 10, offset: 0 }).$object; However, my goal is to enhance the functionality by implementing a feature wher ...

Ensure that the checkbox is always selected

My goal is to have a checkbox always checked unless we intentionally want it to be unchecked. Check out the following HTML code: <input type="checkbox" class="custom-control-input" [(ngModel)]="productDetails.iscanRetrunable" name="isc ...

Unable to export JavaScript module

In my JavaScript project, I have a module named utilities stored in a file called utilities.js. This module contains basic functions that I want to keep hidden from the global namespace. I know that in order to achieve this, I need to create a module, expo ...

Completing a React form using the Google Chrome developer console

Recently, I have been attempting to create a bot that can automatically fill out forms on a website by running a script in the Chrome console. (I want to clarify that this is entirely legal.) However, I've encountered an issue due to the fact that the ...

The functionality of ng-click or ng-href within a repeated table row is not functioning as expected

The following code snippet is from the HTML page: <tr ng-repeat="res in result" ng-click='go()'> <td>{{res.value1}}</td> <td>{{res.value2}}</td> <td>{{res.value3}}</td> <td>{{res.v ...

Exploring the concept of union return types in TypeScript

Hello, I am facing an issue while trying to incorporate TypeScript in a way that may not be its intended use. I have created a custom hook called useGet in React which can return one of the following types: type Response<T> = [T, false, false] | [nul ...

jQuery - Enlarge Tree View to the level of the selected node

I am struggling to figure out how to expand the tree view up to a selected node level. If anyone has any ideas on how to accomplish this, please let me know. For instance, if we click on 'Parent d' in the 'Category list', I want to exp ...

Difficulty in displaying YQL JSON Results with HTML/JavaScript

When utilizing the subsequent YQL query along with XPATH to retrieve data from certain elements on a webpage: select * from html where url="http://www.desidime.com" and xpath='//h5[@class="product_text"]' I am attempting to showcase the outc ...

Angular tutorial on splitting a JSON array

I am looking to extract a portion of a JSON array in Angular. The array looks like the one in the image below.https://i.stack.imgur.com/w0hqC.png Below is the code snippet: export class AppComponent { color: string = 'green'; public stocklis ...

Achieve full height without scrolling in React

I am facing an issue where the height:100% property is not working to fill the remaining area on the screen. A red outlined area represents the border radius, while the highlighted yellow space should have been filled: https://i.stack.imgur.com/ZQNkw.png ...

Connectivity issue: Socket.io fails to register user upon connection

Upon connecting to the page, I expect to see the message 'a user connected' printed on the command line using node.js. However, this message is not being displayed, indicating that the user's visit to the page is not being registered (all ac ...

Differences Between Object.keys().map() and Array.map()

I'm seeking a rationale for why Approach A is considered superior to Approach B. Approach A: const transformCompanyOptions = (companies: Array<{id: string, name: string}>, selectedId: string) => { return companies.map(key => { retu ...

Stopping the execution in JavaScript: Is there a way to do it?

Here is a link with embedded JavaScript code: <a style="padding: 5px;" onclick="confirmMessage(); $('contact_693_').show(); $('errors_693_').hide(); this.hide(); $('dont_693_').show();; return false;" id="the_link_693_" hr ...

Tips on incorporating redirect link to Material UI icon's onclick in React

I'm encountering some issues when trying to add a function to the VideocamOutlinedIcon on line 232. I want this function to include an onclick event that redirects the user to an external domain link in a new tab. Despite attempting various solutions, ...

Using ngTable within an AngularJS application

While working on my angularjs application, I encountered an issue with ngtable during the grunt build process. It seems that the references are missing, resulting in the following error: Uncaught Error: [$injector:modulerr] Failed to instantiate module pa ...

Performing a cross-domain JSON Get request with JQuery

Struggling with a simple JSON get request to an API on a domain that I don't have control over. Here's the code I'm using: $(document).ready(function () { $.ajax({ type: 'GET', url: 'http://pu ...

Issues with AngularJS binding not functioning properly within JSFiddle

When I make a jsfiddle page: jquery datatable with Angularjs - individual column searching none of the angularjs bindings seem to be functioning properly, as it only displays {{n1}} instead of showing the expected bound content. The external resource ...

Disabling dates in Kendo Date Time Picker (Angular): An easy guide

<input id="startDate" kendo-date-time-picker k-ng-model="vm.startDate" k-on-change="vm.updateStartDate()" required /> Can someone please explain how to incorporate disabled dates into this date picker without utilizi ...

Using Try and Catch effectively - tips and strategies

As I delve into learning JavaScript on my own, one topic that caught my attention is the try/catch structure. The tutorial I came across only covers how to implement it, but lacks in explaining its practical applications. Is there anyone who can shed som ...