Ng-repeat - 来自模态的 "Are you sure to delete ?"

Ng-repeat - "Are you sure to delete ?" from a modal

我正在从 Django API 中检索对象(项目)列表。

  my_app.factory('list_of_items', function($resource) {
        return $resource(
            '/api/petdata/') });

然后我在 ng-repeat 内的 html 页面中显示所有内容:

<div ng-controller="ModalDemoCtrl">
    <div ng-repeat="item in items | filter:{display:'1'} | orderBy: 'item_name'">
     <div class="box box-widget widget-user">
    {{ item.pet_name }}{% endverbatim %}
    <button type="button" class="btn btn-box-tool" ng-click="askDelete(item)" href="#"><i class="fa fa-times"></i></button>
    </div>
<div>

到目前为止一切都很好。 然后我希望用户能够通过单击 html 页面上的按钮来删除其中一项。 在这里删除是什么意思: 1. 通过将 属性 "display:1" 更改为 "display:0" 来更新 API 数据库。 2. 从 ng-repeat 中删除项目。

我想制作一个 "Are you sure" 模式来确认删除过程。 这是 askDelete 函数。

angular.module('djangular-demo').controller('Ctrl_List_Of_Pets', function($scope, $http, $window,$filter,list_of_pets,pet_by_id,$uibModal) {

$scope.items = list_of_items.query()

  $scope.askDelete = function (idx,item,size,parentSelector) {
    // console.log("PET",$scope.pet_to_be_undisplayed);
    var parentElem = parentSelector ? 
      angular.element($document[0].querySelector('.modal-demo ' + parentSelector)) : undefined;
    var modalInstance = $uibModal.open({
      animation: true,
      ariaLabelledBy: 'LOL',
      ariaDescribedBy: 'modal-body',
      templateUrl: "myModalContent.html",
      controller: function($scope) {
  $scope.ok = function() {
    modalInstance.close();
  };


  $scope.cancel = function() {
    modalInstance.dismiss('cancel');
  };

      },
      size: size,
      appendTo: parentElem,
      resolve: {
      }
    });

    modalInstance.result.then(function() {
      reallyDelete(item);
    });

  };

    var reallyDelete = function(item) {

      $scope.entry = items_by_id.get({ id: item.id }, function() {
      // $scope.entry is fetched from server and is an instance of Entry
      $scope.entry.display = 0;
      $scope.entry.$update({id: $scope.entry.id},function() {
        //updated in the backend
      });
    });  

    $scope.items = window._.remove($scope.items, function(elem) {
      return elem != item;
    });
  };

});

什么有效: 使用 PUT 请求更新数据库(未提供代码)。

什么不起作用: 从 ng-repeat 中删除该项目永远行不通。或者它抛出一个像这里这样的错误,因为它不知道 window._.remove 或者它不知道 $scope.items。这取决于我的尝试。或者模式关闭并且没有更新 ng-repeat 列表,没有刷新并且每个项目都保留而 PUT 请求更新有效。

我阅读了所有关于范围继承的文章,我认为我在这里没有犯任何错误,但我可能是错的。我已经挣扎了太久所以我 post 在这里!

您有什么建议可以让它发挥作用吗?

谢谢你的赏赐。

第一个:

$scope.askDelete = function (idx,item,size,parentSelector) 接收项目索引、项目、大小和父选择器...并且您正在调用 ng-click="askDelete(item)"

我假设您正在尝试传递该项目,但在 askDelete 中,您收到的第一个参数是索引(也许您应该 ng-click="askDelete($index)"?)

第二个:

reallyDelete 中,您为什么要像这样删除项目数组:

$scope.items = window._.remove($scope.items, function(elem) {
  return elem != item;
});

?

恕我直言,如果我们这样做,代码会更简洁:

$scope.items.splice(idx, 1) //<- idx would be the idx of the entry in the items

你可能想看看Splice