Delete a record using Restangular

I am using Restangular in my AngularJS application. I have a table with a delete link for each item. I would like to delete the item and automatically delete the row. But since it only removes from the database. How can I reorganize things so that it automatically updates the DOM?

// 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 like to find an example of this - even with the Angular resource. All admin / data demo files work with static data.

+7
javascript angularjs angularjs-ng-repeat restangular
source share
2 answers

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

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

Note that they use underscore.js without , which remove the element from the array. I assume that if they publish this example on their readme page, this means that the .remove() function does not remove the original item from the collection. This makes sense, since not every deleted item you want to remove from the collection itself.

Also, what happens if the DELETE $HTTP request fails? You do not want to delete the item then, and you must be sure that you will deal with this problem in your code.

+19
source share

In my case, the above did not 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); }); }; 
+2
source share

All Articles