AngularJS RESTful Web Service - Delete row from ta

2019-06-08 09:20发布

问题:

I need to delete a row from my table but I don't want to reload or refresh all my table in order to see the updated rows.

var demoApp = angular.module("demoApp", ["ngResource"]);

// Controller
demoApp.controller("categoryController", function($scope,   deleteCategorieService, categoriesService){
    $scope.categories = categoriesService.query();

    $scope.deleteCategory = function(id){
        deleteCategoryService.deleteCategory({id: id});
        // I want to avoid this method to refresh my table.
        // $scope.categories = categoriesService.query();
    }; 
 });

// Factories
demoApp.factory("deleteCategorieService", function($resource){
    return $resource("/demopro/deleteCategory/:id", {}, {
        deleteCategory: {
            method: "DELETE",
            params: {id: "@id"}
        }
    });
});

demoApp.factory("categoriesService", function($resource){
    return $resource("/demopro/categories", {}, {
        listAllCategories : {
           method: "GET",
           isArray: true
        }
    });
});

How can I do that?

回答1:

You still have to make the server call to delete the item but, to simply remove it from the view without reloading the whole list from the server, loop through your $scope.categories looking for the id of the item you are deleting, when found, remove from the array.

var i = $scope.categories.length;
while (i > 0) {
  if ($scope.categories[i].id === id) {
    $scope.categories.splice(i, 1);
    break;
  }
  i--;
}

You can also do a positive loop which I normally do but I recently was told this back-to-front loop is supposed to be much faster. YMMV.

 for (var i = 0; i < $scope.categories.length; i++) {
   if ($scope.categories[i].id === id) {
     $scope.categories.splice(i, 1);
     break;
   }
 }

If you are using 2-way binding in your view, the HTML should update without the item you just deleted without having to requery the entire collection.



回答2:

If the problem is that you want to avoid the flickering that happens when refreshing the list, just update the list in the success callback. Something like:

$scope.deleteCategory = function(id){
    deleteCategoryService.deleteCategory({id: id},
        function(success) {
            $scope.categories = categoriesService.query();
        });
};