Two solutions: after you have completed the deletion, remove the user from the users array by making a fragment:
$scope.DeleteUser = function (index) { var UserID = $scope.users[index].Id; $http.delete('/api/users/' + UserID).then(function(del) { $scope.users.splice(index,1); }); }
You can get the user index using $ index in your ng replay, but since your code may be asynchronous, this is not recommended.
Or you can just make another access from your API as soon as your deletion is allowed.
$scope.DeleteUser = function (index) { var UserID = $scope.users[index].Id; $http.delete('/api/users/' + UserID).then(function(del) { $http.get('/api/users').then(function(data){ $scope.users = data; }); }); }
But ... What if the person using your application removes users faster than your API can?
The first solution will not work for sure, and the second is unlikely to support you DOM clean until all requests return in the same order in which they were sent.
One solution is to prevent any API request as long as the other is already waiting.
In JavaScript, because functions are actually executable. Objects can have properties. Therefore, we will add the isBusy property to the DeleteUser function to know when it is already being processed.
$scope.DeleteUser = function (index) { if(!$scope.DeleteUser.isBusy){ var UserID = $scope.users[id].Id; $scope.DeleteUser.isBusy = true; $http.delete('/api/users/' + UserID).then(function(del) { $scope.users.splice(id,1); $scope.DeleteUser.isBusy = false; }); } }
EDIT:
Update the code to use .then() on the $http promise object since .success() now deprecated.
source share