在AngularJS自定义DataTable

时间:2016-11-24 12:06:52

标签: jquery angularjs datatable angular-filters

我的AngularJS应用程序中有一个自定义数据表。

App.js:

myApp.factory('dataTable', ['$filter', 'ngTableParams', '$rootScope', function ($filter, ngTableParams, $rootScope) {

    var factoryDefinition = {
      render: function($scope, config, componentId, data) {

        if(!config) config ={};
        var config = angular.extend({}, {page:1, count:10}, config)

        $scope[componentId] = new ngTableParams(config, {
            total: data.length, // length of data
            getData: function ($defer, params) {
                // organize filter as $filter understand it (graph object)
                var filters = {};
                var val = $rootScope.mysearch;
                var key = "firstname";
                angular.forEach(params.filter(), function (val, key) {
                    var filter = filters;
                    var parts = key.split('.');
                    for (var i = 0; i < parts.length; i++) {
                        if (i != parts.length - 1) {
                            filter[parts[i]] = {};
                            filter = filter[parts[i]];
                        }
                        else {
                            filter[parts[i]] = val;
                        }
                    }
                });
                // use build-in angular filter
                var filteredData = params.filter() ?
                        $filter('filter')(data, filters) :
                        data;
                var orderedData = params.sorting() ?
                        $filter('orderBy')(filteredData, params.orderBy()) :
                        data;
                params.total(orderedData.length); // set total for recalc pagination
                $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                $scope.pageNumber = params.page();
                $scope.itemsPerPage = params.count();
            }
        }); 


      }
    }

    return factoryDefinition;
  }
]);

我了解过滤器适用于params.filter(), function (val, key)和&#39; val&#39;返回值和&#39;键&#39;返回过滤器的名称。

HTML:

<div class="widget-content  table-container" ng-controller="getEmployeesController" >

                <table ng-table="employeesList" show-filter="true" class="table table-striped table-bordered">
                    <tr ng-repeat="employee in $data">
                        <td data-title="'#'">
                           {{ (itemsPerPage * (pageNumber-1)) + $index+1 }}
                        </td>
                        <td data-title="'First Name'" sortable="'firstName'" filter="{ 'firstName': 'text' }">
                            {{employee.firstName}}
                        </td>
</tr>
</table>
</div>

过滤在数据表中正常工作。但是我想让它根据另一个控制器中的搜索字符串设置过滤器。

控制器是:

myApp.controller('getUserHeader', ['$scope', 'commonServices', 'dataTable', '$window', '$rootScope', '$location', '$filter', function ($scope, commonServices, dataTable, $window, $rootScope, $location, $filter) {
    commonServices.getReservations().then(function (result) {
        $scope.data = result.data;
        $scope.data.userName = $rootScope.userInfo.UserName;
        $scope.data.userId = $rootScope.userInfo.UserId;
        commonServices.getEmployee($scope.data.userId).then(function (result) {
            $scope.data = result.data;
        });
        $scope.applySearch = function () {

            $rootScope.mysearch = $scope.mysearch;
            $rootScope.null = null;

            $location.path("/employees");
        }
});
}]);

当用户在过滤字符串中键入并将其保存到$ rootscope并且可从所有控制器访问时,将调用函数applySearch

我将此值保存到关键字&#39; val&#39;并设置&#39;键&#39;的值as&#34; firstname&#34;在控制器内部。在输入字符串时,页面将重定向到存在数据表的$location.path("/employees");。值将进入控制器myApp.factory('dataTable'),但不会进行过滤。控件在angular.forEach(params.filter(), function (val, key) {处中断。它没有返回任何错误消息。

有人可以告诉我如何手动将这些值传递给DataTable指令以使其正常工作吗?

我将分享一些控制台的屏幕截图,向您展示那里发生了什么。可悲的是,我不知道如何创造一个这样的傻瓜。

从数据表中进行过滤:

尝试从外部搜索栏进行过滤时: enter image description here

在第一种情况下,过滤工作正常。但它没有发生在第二种情况。希望我能很好地解释我的情况并提供所有必需的数据。

更新

我可以通过将过滤器直接硬编码到DataTable指令中来进行一些改进。

在函数内添加了if (!config) config = { filter: { 'firstName': $rootScope.mysearch } };,如下所示。

App.js:

//Datatable
myApp.factory('dataTable', ['$filter', 'ngTableParams', '$rootScope', function ($filter, ngTableParams, $rootScope) {

    var factoryDefinition = {
      render: function($scope, config, componentId, data) {
          if (!config) config = { filter: { 'firstName': $rootScope.mysearch } };

        var config = angular.extend({}, {page:1, count:10}, config)

        $scope[componentId] = new ngTableParams(config, {
            total: data.length, // length of data
            getData: function ($defer, params) {
                // organize filter as $filter understand it (graph object)
                var filters = {};
                var val = $rootScope.mysearch;
                var key = "firstname";

                angular.forEach(params.filter(), function (val, key) {
                    var filter = filters;
                    var parts = key.split('.');
                    for (var i = 0; i < parts.length; i++) {
                        if (i != parts.length - 1) {
                            filter[parts[i]] = {};
                            filter = filter[parts[i]];
                        }
                        else {
                            filter[parts[i]] = val;
                        }
                    }
                });
                // use build-in angular filter
                var filteredData = params.filter() ?
                        $filter('filter')(data, filters) :
                        data;
                var orderedData = params.sorting() ?
                        $filter('orderBy')(filteredData, params.orderBy()) :
                        data;
                params.total(orderedData.length); // set total for recalc pagination
                $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                $scope.pageNumber = params.page();
                $scope.itemsPerPage = params.count();
            }
        }); 


      }
    }

    return factoryDefinition;
  }
]);

数据表现在可以按预期过滤,但我不希望它被硬编码。我想注入过滤器而不是硬编码它可能在控制器内部。我该怎么注射它?

0 个答案:

没有答案