我有一个带有项目列表的角度应用程序。我试图实现自定义的“确认删除”模式,以便当用户单击项目旁边的“删除”按钮时,该模式将打开以确认删除。单击“是”后,将触发deleteItem()函数。我的问题是服务器返回的删除请求找不到404。当我使用标准的jquery确认对话框时,它可以工作,因此我猜测项目ID不会通过模式传递给delete函数。有人可以帮忙吗?
<div class="span6"> <table class="table table-striped table-condensed"> <thead> <tr> <th style="min-width: 80px;">Name:</th> <th style="width:20px;"> </th> <th style="width:20px;"> </th> </tr> </thead> <tbody> <tr ng-repeat="item in items | filter:query | orderBy:orderProp"> <td>{{ item.name }}</td> <td><a ng-click="editItem(item.id)" class="btn btn-small btn-primary">Edit</a></td> <td><a ng-click="openModal(item.id)" class="btn btn-small btn-success">Delete</a></td> </tr> </tbody> </table> <modal-dialog show='modalShown' id = "itemModal" width='300px' height='40%'> <p>Are you sure you want to delete this item?<p> <button ng-click = "deleteItem(item.id)" class = "link">Yes</button> </modal-dialog> </div>
这是控制器:
angular.module('myApp.controllers') .controller('ItemCtrl', ['$scope', 'ItemsFactory', 'ItemFactory', '$location', '$route', function ($scope, ItemsFactory, ItemFactory, $location, $route) { $scope.modalShown = false; //callback for ng-click 'deleteItem': $scope.openModal = function (itemId) { $scope.modalShown = !$scope.modalShown; }; //callback for ng-click 'deleteItem': $scope.deleteItem = function (itemId) { ItemFactory.delete({ id: itemId }).$promise.then(function (items){ $scope.items = items; $location.path('/items'); $route.reload(); }, function (err) { console.error(err); }); // } };
的item仅是“已知的”由所创建的范围内ngRepeat的每个元素。 <modal-dialog>不在此范围内,也不了解item。
item
ngRepeat
<modal-dialog>
您可以这样重构代码:
// In HTML: <modal-dialog ...> ... <button ng-click="deleteItem()" ... // In controller: $scope.modalShown = false; $scope.itemToDeleteId; ... $scope.openModal = function (itemId) { $scope.itemToDeleteId = itemId; $scope.modalShown = true; }; ... $scope.deleteItem = function () { if (!$scope.itemToDeleteId) { return; } var itemId = $scope.itemToDeleteId; $scope.itemToDeleteId = null; ...