AngularJS RESTful Web Service - Delete row from table

♀尐吖头ヾ 提交于 2019-12-08 06:42:31

问题


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();
        });
};


来源:https://stackoverflow.com/questions/30573582/angularjs-restful-web-service-delete-row-from-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!