我在我的 AngularJS 应用程序中使用 Restangular。我有一个表,每个项目都有一个删除链接。我想删除该项目并自动删除该行。但事实上它只从数据库中删除。我如何重构事物以便 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>
我也很想找到这样的例子——即使是 Angular 资源。所有管理/数据表演示似乎都适用于静态数据。
最佳答案
根据 Restangular https://github.com/mgonto/restangular#restangular-methods他们提到你应该使用原始项目并用它运行一个 Action ,所以在你的 html 代码中你应该:
<li ng-repeat="product in products">
<a href="#" ng-click="delete(product)"></a>
</li>
然后在你的 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);
});
};
注意他们使用了 underscore.js without 这将从数组中删除元素。我想如果他们在自述文件页面中发布该示例,则意味着 .remove()
函数不会从集合中删除原始项目。这是有道理的,因为并非您删除的每一项都希望从集合本身中删除。
此外,如果 DELETE $HTTP
请求失败会怎样?那时您不想删除该项目,并且必须确保在您的代码中处理该问题。
关于javascript - 使用 Restangular 删除条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18523806/