AbuTaha AbuTaha - 4 months ago 70
AngularJS Question

In Angularjs, how to update table data after deleting a row from it

I am using the angularjs to call Asp.net Web API. After I delete a row from the table?

I also did not find the solution in w3schools.

My HTML code

<tr ng-repeat="user in users | filter: search">
<td>{{ user.Id }}</td>
<td>{{ user.FullName }}</td>
<td>{{ user.Mobile }}</td>
<td>{{ user.Birthdate }}</td>
<td>{{ user.Gender }}</td>
<td>{{ user.AcademicLevel }}</td>

<td>


My Angularjs code

$scope.DeleteUser = function (id) {
UserID = $scope.users[id].Id;
$http.delete('/api/users/' + UserID).success(function (data) {
(function (data) {
$scope.error = "error " + data;
});

}


I searched in Stackoverflow, I found some of these where they did not work for me, they confused me.

$scope.refresh()
$scope.apply();

Answer

First of all, handling server requests in your controller is a bad idea. As a rule of thumb, use services to delegate calls to the server, and use the controller for "gluing" up your models to your view.

There are a few issues in your code, it should look something like this:

$scope.DeleteUser = function (id) {
    var userId = $scope.users[id].Id;
    $http.delete('/api/users/' + userId)
          .success(function (data) {
             $scope.error = "error " + data;
          });
}

Even if the call to the server was successful, you never updated your front-end model. What you have read on other topics regarding $scope.refresh(), I suppose that has the purpose of fetching the data again, like so:

$scope.refresh = function(){
    $http.get('/api/users')
          .success(function(data){
               $scope.users = data;
          });
}

So in order the refresh your view, you must update your model.

$scope.DeleteUser = function (id) {
    var userId = $scope.users[id].Id;
    $http.delete('/api/users/' + userId)
          .success(function (data) {
             //either this
             $scope.refresh();
             //or this
             $scope.users.splice(id,1);
          });
}