AngularJS RESTful Web Service - Delete row from table

你说的曾经没有我的故事 提交于 2019-12-07 07:52:29

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.

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