2013-08-30 85 views
7

我在AngularJS應用程序中使用Restangular。我有一個表格,每個項目都有一個刪除鏈接。我想刪除該項目並自動刪除該行。但事實是,它只從數據庫中刪除。我如何重構事件,以便DOM自動更新?使用Restangular刪除條目

// 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> 

我也很想找到一個例子 - 即使有Angular資源。所有的管理員/數據表演示似乎都能從靜態數據中工作。

+0

如果項目從'$ scope.products'集合中刪除,您可以檢查代碼嗎? – Chandermani

+0

它沒有。我想我必須從資源和scope.products中刪除。我想我正在尋找一種不必這樣做的方式 - 但可能不會。 – cyberwombat

+0

你可以隨時看看restangular的來源,並驗證:) – Chandermani

回答

19

根據Restangular https://github.com/mgonto/restangular#restangular-methods他們提到,你應該使用原來的項目,並運行它的動作,所以在你的HTML代碼,你應該:

<li ng-repeat="product in products"> 
    <a href="#" ng-click="delete(product)"></a> 
</li> 
在你的控制器

然後:

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

注意,它們使用underscore.js而不使用,它將從陣列中刪除元素。我猜如果他們在自己的自述頁面中發佈該示例,這意味着.remove()函數不會從集合中刪除原始項目。這是有道理的,因爲不是每個你刪除的項目都想從集合中刪除。

另外,如果DELETE $HTTP請求失敗會發生什麼?然後,您不想刪除該項目,並且必須確保在代碼中處理該問題。

+0

有道理。儘管如此,我還沒有工作。 product.remove()調用錯誤的URL - 不知道爲什麼 - 它做一個DELETE /產品而不是DELETE /產品/ ID – cyberwombat

+4

啊解決了!我使用Mongo,因此它發送_id而不是id。我需要這個配置RestangularProvider.setRestangularFields({id:「_id」}); – cyberwombat

+0

這完全適合我。但是,如果您從$ scope.products中刪除最後一個元素,那麼它不再是一個重複項目,因此您無法將項目添加回它。我預計它會離開核心重振的東西,但事實並非如此。任何解決方案? –

2

在我的情況下,上述不起作用。我必須執行以下操作:

$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); 
     }); 
    }; 
+0

這也適用於我。謝謝。 –