简体   繁体   English

单击一次按钮后无法删除使用指令创建的表的选定行

[英]Unable to delete selected rows of a table created with directive on single button click

I am trying to implement the functionality of deleting multiple selected rows of table with single button click. 我正在尝试实现通过单击按钮删除表的多个选定行的功能。 When I implement this functionality on a simple table created without directive it works fine: Working Plunker 当我在没有指令的简单表上实现此功能时,它可以正常工作工作柱塞

But when I try to implement the same on the table created using reusable directive, it does not work: Non Working Plunker 但是,当我尝试在使用可重用指令创建的表上实现相同功能时,它将无法正常工作:无法正常工作

Below is the code for my table with directive: 以下是我的带有指令的表的代码:

Index HTML: 索引HTML:

<!DOCTYPE html>
<html ng-app="demoapp">

<head>
    <title>My App</title>
    <link rel="stylesheet" href="style.css">
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.js"></script>
    <script src="//cdn.jsdelivr.net/angular.bootstrap/0.11.0/ui-bootstrap-tpls.min.js"></script>
    <script src="script.js"></script>
</head>

<body>
    <div ng-controller="TableCtrl" class="container">
        <div class="row">
            <div class="col-lg-12">
                <div class="">
                    <div class="table-responsive">
                        <div class="ng-data-table" ng-dt="Demo"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

_dataTable.html: _dataTable.html:

<table class="table table-bordered table-condensed table-hover">
    <thead>
    <tr>
        <th ng-repeat="th in ngDt.Headers" class="text-center">
            {{th.Name}}
            <input ng-if="th.Type==='Selectable'" type="checkbox" ng-checked="ngDt.isSelectedAllRows()" ng-click="ngDt.selectAllRows($event)" class=""/>
            <a ng-if="th.Type === 'Selectable' && ngDt.IsDeleteMultipleRowsIconVisible === true " class="text-danger delete-icon" ng-click="ngDt.deleteRow()">
                <i class="fa fa-trash-o"></i>
            </a>
        </th>
    </tr>
    </thead>
    <tbody>
    <tr bindonce ng-repeat="row in ngDt.Rows" ng-class="ngDt.getRowClass(row);">
        <td ng-repeat="cell in ngDt.Cells" class="text-center col-lg-6 col-md-6 col-sm-6 col-xs-6">
            {{cell.Type === 'Normal' ? row[cell.Name] : ''}}
            <input ng-if="cell.Type === 'Selectable'" type="checkbox" ng-checked="ngDt.isRowSelected(row)" ng-click="ngDt.selectRowChanged($event,row)" />
        </td>
    </tr>
    </tbody>
</table>

JS: JS:

// Code goes here
var appRoot = angular.module('demoapp', ['ngRoute', 'ui.bootstrap']);



  /*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
 //-------------------Directive-------------------//
/*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
appRoot.directive('ngDataTable', function () {
    return {
        restrict: 'C',
        replace: true,
        scope: {
            ngDt: "=ngDt"
        },
        templateUrl: "_dataTable.html"
    };
});

  /*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
 //-------------------Directive-------------------//
/*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/



  /*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
 //--------------------Service--------------------//
/*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
appRoot.service('MyService', function () {
    return {
        SelctedIds: [],
        updateSelected: function (action, id) {
            if (action === 'add' && this.SelctedIds.indexOf(id) === -1) {
                this.SelctedIds.push(id);
            }
            if (action === 'remove' && this.SelctedIds.indexOf(id) !== -1) {
                this.SelctedIds.splice(this.SelctedIds.indexOf(id), 1);
            }
        },
        selectRowChanged: function ($event, id) {
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            this.updateSelected(action, id);
            return this.SelctedIds;
        },
        selectAll: function ($event, obj, identifierKey) {
            var tempAllIds = [];
            angular.forEach(obj, function (value, key) {
                tempAllIds.push(value[identifierKey]);
            });
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            for (var i = 0; i < tempAllIds.length; i++) {
                var id = tempAllIds[i];
                this.updateSelected(action, id);
            }
            return this.SelctedIds;
        },
        isRowSelected: function (id) {
            return this.SelctedIds.indexOf(id) >= 0;
        },
        getSelectedClass: function (id, selectionClassName) {
            return this.isRowSelected(id) ? selectionClassName : '';
        },
        isSelectedAllRows: function (obj) {
            if (obj !== undefined) {
                return this.SelctedIds.length === obj.length;
            } else {
                return false;
            }

        }
    };
});
  /*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
 //--------------------Service--------------------//
/*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/

appRoot.controller('TableCtrl', function ($scope, MyService) {
    $scope.Demo = {};

    $scope.Demo.Rows = [
        { "Id": "1", "Name": "Row1", "IsDeleted": false },
        { "Id": "2", "Name": "Row2", "IsDeleted": false },
        { "Id": "3", "Name": "Row3", "IsDeleted": false }
    ];

    $scope.Demo.Headers = [
        { "Name": "Select", "Type": "Selectable" },
        { "Name": "Name", "Type": "Normal" }
    ];

    $scope.Demo.Cells = [
        { "Name": "Select", "Type": "Selectable" },
        { "Name": "Name", "Type": "Normal" }
    ];



    $scope.Demo.IsDeleteMultipleRowsIconVisible = false;

    //----------------Multiple Delete----------------//
    $scope.Demo.SelectedRows = [];
    $scope.Demo.selectRowChanged = function ($event, row) {
        var id = row.Id;
        $scope.Demo.SelectedRows = MyService.selectRowChanged($event, id);
    };

    $scope.Demo.isRowSelected = function (row) {
        var id = row.Id;
        return MyService.isRowSelected(id);
    };

    $scope.Demo.selectAllRows = function ($event) {
        $scope.Demo.SelectedRows = MyService.selectAll($event, $scope.Demo.Rows, "Id");
    };


    $scope.Demo.isSelectedAllRows = function () {
        return MyService.isSelectedAllRows($scope.Demo.Rows);
    };

    $scope.Demo.getRowClass = function (row) {
        var className = "";
        if ($scope.Demo.SelectedRows.length > 0) {
            className = MyService.getSelectedClass(row.Id, "bg-danger-muted");
        }
        if ($scope.Demo.SelectedRows.length > 0) {
            $scope.Demo.IsDeleteMultipleRowsIconVisible = true;
        } else {
            $scope.Demo.IsDeleteMultipleRowsIconVisible = false;
        }
        return className;
    };

    $scope.Demo.deleteRow = function () {
        for (var i = 0; i < $scope.Demo.SelectedRows.length; i++) {
            for (var j = 0; j < $scope.Demo.Rows.length; j++) {
                if ($scope.Demo.SelectedRows[i] === $scope.Demo.Rows[j].Id) {
                    $scope.Demo.Rows[j].IsDeleted = true;
                }
            }
        }
    };
    //----------------Multiple Delete----------------//
});

What am I missing? 我想念什么? Is there any better way to acomplish the same task to reduce the amount of code and make it more reusable? 有没有更好的方法来完成同一任务以减少代码量并使其更可重用?

You could use ng-repeat="row in ngDt.Rows| filter: {IsDeleted: false}" filter the Rows on basis of IsDeleted flag. 您可以ng-repeat="row in ngDt.Rows| filter: {IsDeleted: false}"使用ng-repeat="row in ngDt.Rows| filter: {IsDeleted: false}"根据IsDeleted标志过滤行。

Markup 标记

<tr bindonce ng-repeat="row in ngDt.Rows| filter: {IsDeleted: true}" ng-class="ngDt.getRowClass(row);">
    <td ng-repeat="cell in ngDt.Cells" class="text-center col-lg-6 col-md-6 col-sm-6 col-xs-6">
        {{cell.Type === 'Normal' ? row[cell.Name] : ''}}
        <input ng-if="cell.Type === 'Selectable'" type="checkbox" ng-checked="ngDt.isRowSelected(row)" ng-click="ngDt.selectRowChanged($event,row)" />
    </td>
</tr>

Plunkr Here 普伦克在这里

Answer for the second part of my question, may be helpful to someone: 回答我问题的第二部分,可能对某人有所帮助:

Is there any better way to acomplish the same task to reduce the amount of code and make it more reusable? 有没有更好的方法来完成同一任务以减少代码量并使其更可重用?

I improved the delete functionality little to reduce the code. 我改进了删除功能,很少减少代码。 Plunker Plunker

Index Html: 索引HTML:

<div ng-controller="TableCtrl" class="container">
        <div class="row">
            <div class="col-lg-12">
                <div class="">
                    <div class="table-responsive">
                        <div class="ng-data-table" ng-dt="Demo"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

_dataTable.html: _dataTable.html:

<table class="table table-bordered table-condensed table-hover">
    <thead>
        <tr>
            <th ng-repeat="th in ngDt.Headers" class="text-center">
                {{th.Name}}
                <input ng-if="th.Type==='Selectable'" type="checkbox" ng-model="ngDt.IsAll" ng-click="ngDt.selectAllRows()" />
                <a ng-if="th.Type === 'Selectable' && ngDt.isShowDeleteBtn() === true " class="text-danger delete-icon" ng-click="ngDt.removeSelectedRows()">
                    <i class="fa fa-trash-o"></i>
                </a>
            </th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="row in ngDt.Rows" ng-class="{'warning' : row['IsSelected']}">
            <td ng-repeat="cell in ngDt.Cells">
                <input ng-if="cell.Type==='Selectable'" type="checkbox" ng-model="row['IsSelected']" ng-change="ngDt.isShowDeleteBtn()" />
                {{(cell.Type==='Normal')?row[cell.Name]:''}}
            </td>
        </tr>
    </tbody>
</table>

JS: JS:

    var appRoot = angular.module('demoapp', []);

//-------------------Directive-------------------//
appRoot.directive('ngDataTable', function () {
    return {
        restrict: 'C',
        replace: true,
        scope: {
            ngDt: "=ngDt"
        },
        templateUrl: "_dataTable.html"
    };
});
//-------------------Directive-------------------\\

//--------------------Service--------------------//
appRoot.service('MyService', function () {
    return {
        isShowDeleteBtn: function ($scope) {
            var cnt = 0;
            for (var i = 0; i < $scope[$scope.ObjName].Rows.length; i++) {
                if ($scope[$scope.ObjName].Rows[i]['IsSelected'] === true) {
                    cnt++;
                    break;
                }
            }
            return (cnt > 0);
        },
        selectAllRows: function ($scope) {
            //check if all selected or not
            if ($scope[$scope.ObjName].IsAll === false) {
                //set all row selected
                angular.forEach($scope[$scope.ObjName].Rows, function (row, index) {
                    $scope[$scope.ObjName].Rows[index]['IsSelected'] = true;
                });
                $scope[$scope.ObjName].IsAll = true;
            } else {
                //set all row unselected
                angular.forEach($scope[$scope.ObjName].Rows, function (row, index) {
                    $scope[$scope.ObjName].Rows[index]['IsSelected'] = false;
                });
                $scope[$scope.ObjName].IsAll = false;
            }
        },
        removeSelectedRows: function ($scope) {
            //start from last index because starting from first index cause shifting
            //in the array because of array.splice()
            $scope[$scope.ObjName].SelectedIds = "";
            for (var i = $scope[$scope.ObjName].Rows.length - 1; i >= 0; i--) {
                if ($scope[$scope.ObjName].Rows[i].IsSelected) {
                    if ($scope[$scope.ObjName].SelectedIds === "") {
                        $scope[$scope.ObjName].SelectedIds += $scope[$scope.ObjName].Rows[i].Id;
                    } else {
                        $scope[$scope.ObjName].SelectedIds += "," + $scope[$scope.ObjName].Rows[i].Id;
                    }
                    //delete row from Rows
                    $scope[$scope.ObjName].Rows.splice(i, 1);
                }
            }
        }
    };
});
//--------------------Service--------------------\\

//------------------Controller-------------------//
appRoot.controller('TableCtrl', function ($scope, MyService) {
    $scope.Demo = {};
    $scope.ObjName = "Demo";
    $scope.Demo.IsAll = false;
    $scope.Demo.SelectedIds = "";
    $scope.Demo.Rows = [{ "Id": "1", "Name": "Row1", "IsDeleted": false },{ "Id": "2", "Name": "Row2", "IsDeleted": false },{ "Id": "3", "Name": "Row3", "IsDeleted": false }];

    $scope.Demo.Headers = [{ "Name": "Select", "Type": "Selectable" },{ "Name": "Name", "Type": "Normal" }];

    $scope.Demo.Cells = [{ "Name": "Select", "Type": "Selectable" },{ "Name": "Name", "Type": "Normal" }];

    $scope.Demo.isShowDeleteBtn = function () {
        return MyService.isShowDeleteBtn($scope);
    }

    $scope.Demo.IsAll = false;
    $scope.Demo.selectAllRows = function () {
        MyService.selectAllRows($scope);
    };

    $scope.Demo.removeSelectedRows = function () {
        MyService.removeSelectedRows($scope);
    };
});
//------------------Controller-------------------\\

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM