Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting entry with Restangular

I am using Restangular in my AngularJS app. I have a table with a delete link for each item. I would like to delete the item and have the row automatically removed. But as things are it only deletes from DB. How can I refactor things so that it the DOM is updated automatically?

// The controller
angular.module('myApp').controller('ManageCtrl', function($scope, Restangular) {

  $scope.delete = function(e) {
     Restangular.one('product', e).remove();
  };

  Restangular.all('products').getList({}).then(function(data) {
    $scope.products = data.products;
    $scope.noOfPages = data.pages;
  });
});


 // The view
 <li ng-repeat="product in products">
   <a href="#" ng-click="delete(sheet._id)"></a>
  </li>

I would also love to find an example of this - even with Angular resource. All the admin/data table demos seem to work from static data.

like image 999
cyberwombat Avatar asked Aug 30 '13 02:08

cyberwombat


2 Answers

According to Restangular https://github.com/mgonto/restangular#restangular-methods they mention that you should use the original item and run an action with it, so in your html code you should:

 <li ng-repeat="product in products">
   <a href="#" ng-click="delete(product)"></a>
</li>

Then in your controller:

 $scope.delete = function( product) {
    product.remove().then(function() {
      // edited: a better solution, suggested by Restangular themselves
      // since previously _.without() could leave you with an empty non-restangular array
      // see https://github.com/mgonto/restangular#removing-an-element-from-a-collection-keeping-the-collection-restangularized

      var index = $scope.products.indexOf(product);
      if (index > -1) $scope.products.splice(index, 1);
   });
 };

Notice they use the underscore.js without which will remove the element from the array. I guess that if they post that example in their readme page that means the .remove() function doesn't remove the original item from the collection. This makes sense, since not every item you remove you want removed from the collection itself.

Also, what happens if the DELETE $HTTP request fails? You don't want to remove the item then, and you have to make sure to handle that problem in your code.

like image 170
Gilad Peleg Avatar answered Sep 22 '22 17:09

Gilad Peleg


In my case the above didn't quite work. I had to do the following:

$scope.changes = Restangular.all('changes').getList().$object;

    $scope.destroy = function(change) {
        Restangular.one("changes", change._id).remove().then(function() {
            var index = $scope.changes.indexOf(change);
            if (index > -1) $scope.changes.splice(index, 1);
        });
    };
like image 20
ssedwards Avatar answered Sep 21 '22 17:09

ssedwards