как объединить заголовок клиента и фильтр в ngTable

Я хотел бы создать ngTable, который представляет собой комбинацию примера № 4 (фильтр) и № 18 (пользовательский заголовок) из ngTable сайт. Я не могу заставить его работать. Может ли кто-нибудь показать мне пример? Спасибо!


person user981848    schedule 15.07.2014    source источник


Ответы (2)


Поскольку на самом деле кажется, что простое объединение двух примеров не работает, я создал для вас новую таблицу на основе примера № 18 сайта ng-table, см. http://bazalt-cms.com/ng-table/example/18.

Сначала я добавил новое поле ввода с ng-model, чтобы пользовательский ввод, введенный в поле, можно было привязать к скрипту angularjs. Вот так:

<tr>
    <th colspan="3">
        <input class="form-control" type="text" ng-model="filters.myfilter" placeholder="Filter"  />
    </th>
</tr>

Чтобы переменная использовалась таблицей в качестве фильтра, ее необходимо «объявить» и прикрепить к ng-table (https://github.com/esvit/ng-table/wiki/Настройка-вашей-таблицы-с-ngTableParams) следующим образом:

$scope.filters = {
    myfilter: ''
};

и

$scope.tableParams = new ngTableParams({
            page: 1,            
            count: 10,           
            filter: $scope.filters, //now the filter is attached to the ng-table
        }

Наконец, я использовал немного измененную версию сценария фильтрации в примере №6 (http://bazalt-cms.com/ng-table/example/6) для фильтрации указанной переменной (которая была связана с ng-моделью).

Вот функция getData, которая фильтрует и упорядочивает данные:

getData: function($defer, params) {

    var filtered_data = params.filter() ? $filter('filter')(data, params.filter().myfilter) : data;
    filtered_data = params.sorting() ? $filter('orderBy')(filtered_data, params.orderBy()) : filtered_data;

    $defer.resolve(filtered_data.slice((params.page() - 1) * params.count(), params.page() *   params.count()));
}

Это помогло мне.

Вы можете найти таблицу на этом планке: http://plnkr.co/edit/ntnNqxmKsQoFmSbo0P57?p=preview

person user1491307    schedule 19.07.2014

В ng-table было две проблемы, которые препятствовали настройке заголовка и одновременному отображению фильтров.

  1. ng-table смотрит только на первый элемент tr. Так что они не возможны одновременно.
  2. Если пользователь указывает объявление, он полностью игнорирует шаблон фильтра, поскольку он прикреплен к объявлению, предоставленному ng-таблицей.

Вот исправление, которое я сделал для ng-таблицы, чтобы исправить обе указанные выше проблемы. Измените ng-table.js, как показано ниже:

scope.templates = {
                            header: (attrs.templateHeader ? attrs.templateHeader : 'ng-table/header.html'),
                            pagination: (attrs.templatePagination ? attrs.templatePagination : 'ng-table/pager.html'),
                            filter: 'ng-table/filter.html'
                        };


        var trInsideThead = thead.find('tr');
                                if(thead.length > 0 && trInsideThead.length==1){
                                    var filterTemplate = angular.element(document.createElement('tr')).attr({
                                        'ng-include': 'templates.filter',
                                        'ng-show' : 'show_filter',
                                        'class' : 'ng-table-filters'
                                    });            
                                    var headerTemplate = thead.append(filterTemplate);
                                }
                                else{
                                    var headerTemplate = thead.length > 0 ? thead : angular.element(document.createElement('thead')).attr('ng-include', 'templates.header');                   
                                }

        //Put this in the templatecahce

        $templateCache.put('ng-table/filter.html', '<th ng-repeat="column in $columns" ng-show="column.show(this)" class="filter"> <div ng-repeat="(name, filter) in column.filter"> <div ng-if="column.filterTemplateURL" ng-show="column.filterTemplateURL"> <div ng-include="column.filterTemplateURL"></div> </div> <div ng-if="!column.filterTemplateURL" ng-show="!column.filterTemplateURL"> <div ng-include="\'ng-table/filters/\' + filter + \'.html\'"></div> </div> </div> </th>');

    You need to invert the thead and tbody in the html

    <table>
      <tbody>
      </tbody>
      <thead>
      </thead>
   </table>
person Techie007    schedule 17.11.2014