如何删除ng-table中已删除的行

时间:2014-01-07 06:15:05

标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat angular-ui

我有一个使用ng-table开发的网格,我需要在从服务器端删除后从网格表中删除所选项目。已经尝试再次调用网格加载ajax,但它无法正常工作。

我的控制器

app.controller('blockController', function($scope, $filter, $q, ngTableParams, $sce, Block) {

    // Fetch data from server using RESTful API
    $scope.load = function() {
        // load serverside data using http resource service
        Block.get({}, function (response) { // success
                $scope.results = response.data;
                    var data = response.data; // store result to variable

                    // Start ng-table with pagination
                $scope.tableParams = new ngTableParams({
                                page: 1,            // show first page
                                count: 10           // count per page
                }, {
                                total: data.length, // length of data
                                getData: function($defer, params) {
                                        // use build-in angular filter
                                        var orderedData = params.sorting() ? $filter('orderBy')(data, params.orderBy()) : data;
                                        orderedData = params.filter() ? $filter('filter')(orderedData, params.filter()) : orderedData;
                                        params.total(orderedData.length); // set total for recalc pagination
                                        $defer.resolve($scope.blocks = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                                }
                    });

                // un-check all check boxes
                $scope.checkboxes = { 'checked': false, items: {} };

                // watch for check all checkbox
                $scope.$watch('checkboxes.checked', function(value) {
                    angular.forEach($scope.blocks, function(item) {
                        if (angular.isDefined(item.id)) {
                            $scope.checkboxes.items[item.id] = value;
                        }
                    });
                });

                // watch for data checkboxes
                $scope.$watch('checkboxes.items', function(values) {
                    if (!$scope.blocks) {
                        return;
                    }
                    var checked = 0, unchecked = 0,
                    total = $scope.blocks.length;
                    angular.forEach($scope.blocks, function(item) {
                        checked   +=  ($scope.checkboxes.items[item.id]) || 0;
                        unchecked += (!$scope.checkboxes.items[item.id]) || 0;
                    });
                    if ((unchecked == 0) || (checked == 0)) {
                        $scope.checkboxes.checked = (checked == total);
                    }
                    // grayed checkbox
                    angular.element(document.getElementById("select_all")).prop("indeterminate", (checked != 0 && unchecked != 0));
                }, true);

                }, function (error) { // error
                    $scope.results = [];
                    // error message display here
                });
    }

    // Call REST API
    $scope.load();

    /*
    |------------------------------
    | Delete selected items
    |------------------------------
    */

    $scope.delete = function() {

        var items = [];
        // loop through all checkboxes
        angular.forEach($scope.blocks, function(item, key) {
            if($scope.checkboxes.items[item.id]) {
                items.push(item.id); // push checked items to array
            }  
        });
        // if at least one item checked
        if(items.length > 0) {
            // confirm delete
            bootbox.confirm("Are you sure to delete this data?", function(result) {
                        if(result==true) {
                            for (var i = 0; i < items.length; i++) {
                                // delete using $http resopurce
                                Block.delete({id: items[i]}, function (response) { // success
                                    // remove the deleted item from grid here
                                    // show message
                        }, function (error) { // error
                                // error message display here
                            });
                            }
                        }
                    }); 
        }
    }; // delete

}); // end controller

HTML表格,

            <!-- data table grid -->
            <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" ng-table="tableParams" show-filter="true">
                <tbody>
                        <tr ng-repeat="block in $data">
                    <!-- serial number -->
                    <td data-title="'<?php echo $this->lang->line('sno'); ?>'" style="text-align:center" width="4">{{$index+1}}</td>
                    <!-- Checkbox -->
                    <td data-title="''"  class="center" header="'ng-table/headers/checkbox.html'" width="4">
                       <input type="checkbox" ng-model="checkboxes.items[block.id]" />
                    </td>
                    <!-- Block Name -->
                    <td data-title="'<?php echo $this->lang->line('label_cluster_name'); ?>'" sortable="'block_name'" filter="{ 'block_name': 'text' }">
                        <span ng-if="!block.$edit">{{block.block_name}}</span>
                        <div ng-if="block.$edit"><input class="form-control" type="text" ng-model="block.block_name" /></div>
                    </td>
                    <!-- Description -->
                    <td data-title="'<?php echo $this->lang->line('label_description'); ?>'" sortable="'description'" >
                        <span ng-if="!block.$edit">{{block.description}}</span>
                        <div ng-if="block.$edit"><textarea class="form-control" ng-model="block.description"></textarea></div>
                    </td>
                    <!-- Edit / Save button -->
                    <td data-title="'<?php echo $this->lang->line('label_actions'); ?>'" width="6" style="text-align:center">
                        <a ng-if="!block.$edit" href="" class="btn btn-inverse btn-sm" ng-click="block.$edit = true"><?php echo $this->lang->line('label_edit'); ?></a>
                        <a ng-if="block.$edit" href="" class="btn btn-green btn-sm" ng-click="block.$edit = false;update(block)"><?php echo $this->lang->line('label_save'); ?></a>
                    </td>
                        </tr>
                </tbody>
            </table> <!-- table grid -->

3 个答案:

答案 0 :(得分:12)

一旦服务器确认删除,您应该从数据集中删除已删除的项目。

您可以在删除成功回调中手动执行此操作,而不是仅重新加载完整集合(理论上这也是有效的,但通常会更慢)。

然后从集合中删除该项后,调用tableParams.reload()方法重新加载表,以便更改反映在表中。

您可以在此处找到reload()方法的有效示例:http://plnkr.co/edit/QXbrbz?p=info

希望有所帮助!

答案 1 :(得分:1)

这对我有用:

    $scope.deleteEntity = function (entity) {
    bootbox.confirm("Are you sure you want to delete this entity ?", function (confirmation) {
            if (confirmation) {
                $http.delete("/url/" + entity._id)
                    .success(function (data) {
                        if (data.status == 1) {
                            var index = _.indexOf($scope.data, entity);
                            $scope.data.splice(index, 1);
                            $scope.tableParams.reload();
                        } else {
                        }
                    });
            }
        }
    );
};

答案 2 :(得分:0)

在ng-table的版本1x中,以下代码有效。在此示例中,我使用的是MyController as vm方法,user$resource class object

this.removeUser = function (user,i) {
    user.$remove().then(function () {
        this.tableParams.data.splice(i, 1);                    
    }, function () {
        // handle failure            
    });
});

在HTML表格中调用时,请确保传入$ index作为第二个参数,例如:

<button class="btn btn-danger btn-xs" ng-click="vm.removeUser(user, $index)" title="Delete User">
    <i class="glyphicon glyphicon-trash"></i>
</button>

无需调用tableParams.reload或从服务器重新加载数据。