Search code examples
angularjshttpput

Send angular post request and send to the callback - my object


I have array of events called 'selectedEvents' and i need to send them to the server and get answer one by one. However, i do not know how in the success function the object will be remembered.

 $scope.moveSelectedEventsToAgency = function(){
         var agencyId = $scope.selectedAgency.agencyId;
         for (var i = 0; i< $scope.selectedEvents.length; i++){
            var event = $scope.selectedEvents[i];
            var eventId = event.eventId;

            $http({
                method: 'PUT',
                url: ENV.server_prefix+'/event/ + eventId + "/moveToAgency/" + agencyId'
            }).success(function(data, status) {
                    /* HERE I WANT TO USE EVENT. HOW TO SEND IT HERE FOR DOING ADDITIONAL LOGIC??
                       */

            }).error(function(data, status, params) {
                     /* HERE I WANT TO USE EVENT. HOW TO SEND IT HERE FOR DOING ADDITIONAL LOGIC?
                       */
            });

        }
    };

Solution

  • just enclose the body of for loop in self executing function

    $scope.moveSelectedEventsToAgency = function(){
         var agencyId = $scope.selectedAgency.agencyId;
         for (var i = 0; i< $scope.selectedEvents.length; i++){ 
    
        // ------------------------------
        (function(){
            // since its function scope event and eventId will be ok
            var event = $scope.selectedEvents[i];
            var eventId = event.eventId;
    
            $http({
                method: 'PUT',
                url: ENV.server_prefix+'/event/ + eventId + "/moveToAgency/" + agencyId'
            }).success(function(data, status) {
                    /* HERE I WANT TO USE EVENT. HOW TO SEND IT HERE FOR DOING ADDITIONAL LOGIC??
                       */
    
            }).error(function(data, status, params) {
                     /* HERE I WANT TO USE EVENT. HOW TO SEND IT HERE FOR DOING ADDITIONAL LOGIC?
                       */
            });
    
        })();
    
        }
    };