编辑/添加/删除表格行

时间:2018-04-12 14:03:02

标签: angularjs datatables angular-datatables

我正在使用带有angularjs(https://www.npmjs.com/package/angularjs-datatables

的数据表

当我添加,编辑或删除表格中的一行时,Datatables停止正常运行(排序,分页,搜索,信息等)。我使用推送在表格中添加数据行,拼接以从表格中删除...

以下是我的一些代码:

var app = angular.module('myApp', ['ngSanitize', 'datatables']
    , ['$httpProvider', function ($httpProvider) {
        $httpProvider.defaults.headers.post['X-CSRF-TOKEN'] = $('meta[name=csrf-token]').attr('content');
    }]);
    
app.controller('UserGroupsController', ['$scope', '$http', '$sce', '$timeout', function ($scope, $http, $sce, $timeout) {
    $scope.groups = [];
    $scope.group = {
            id: '',
            name: '',
            description: ''
        };
    $scope.edit_group = {
            index: '',
            id: '',
            name: '',
            description: ''
        };
    
    //Load Groups
    $scope.loadGroups = function () {
        $http.get('/groups/ajax')
            .then(function success(e) {
                $scope.groups = e.data.groups;
            });
    };
    $scope.loadGroups();

    //Create Group
    $scope.createGroup = function () {
        $http.post('/groups/ajax', {
            name: $scope.group.name,
            description: $scope.group.description
        }).then(function success(e) {
            $scope.groups.push(e.data.group);
        }, function error(error) {
        });
    };

    //Update Group
    $scope.updateGroup = function () {
        $http.patch('/groups/ajax/'+$scope.edit_group.id, {
            name: $scope.edit_group.name,
            description: $scope.edit_group.description
        }).then(function success(e) {
            $scope.groups[$scope.edit_group.index] = e.data.group;
        }, function error(error) {
        });
    };
    
    //Delete Group
    $scope.delete = function (index) {
        $http.delete('/groups/ajax/'+$scope.groups[index].id)
            .then(function success(e) {
                $scope.groups.splice(index, 1);
            });
    };
}]);
<body ng-app="myApp">
<div ng-controller="UserGroupsController">
<table datatable="ng" [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="dataTable">
      <thead>
          <tr>
              <th>Name</th>
              <th>Description</th>
              <th>Options</th>
          </tr>
      </thead>
      <tbody>
          <tr class="odd gradeX" ng-repeat="(index, x) in groups">
              <td>{{ x.name }}</td>
              <td>{{ x.description }}</td>
              <td>
                  <button class="btn btn-success" ng-click="edit(index)">Edit</button>
                  <button class="btn btn-danger" ng-click="delete(index)">Delete</button>
              </td>
          </tr>
      </tbody>
  </table>
  </div>
  </body>

0 个答案:

没有答案