how to use filter on button click in angular js

泄露秘密 提交于 2019-12-02 06:34:58

EDIT: Sort both directions

Updated Plunker

To be able to sort in both directions, you should probably use a directive. Using a directive will allow you to create an isolated scope for each of the headings, this way they can keep track of their own current values.

.directive('sortHeader', function($timeout) {
  return {
    restrict: 'E',
    scope: {
      'label': '@',
      'sortstring': '&sortExp',
      'idx': '@index'
    },
    templateUrl: 'sort-header.html',
    link: function(scope, element, attrs) {
      scope.reverse = false;
      element.on('click', function(){
        $timeout(function(){
          scope.reverse = !scope.reverse;
        });
      });
    }
  };
});

This directive has properties for:

  1. label [string] The column header name.
  2. index [string] The column index in the original data set. Note, you cannot use the $index of the ng-repeat.
  3. sort-exp [method] This is a bindable method that you can use to retrieve the current index and reverse values to set your orderBy filter expression. The function passes two values: idx, reverse, in that order. These represent the index of the current element and reverse order as a boolean.

You use the directive as follows:

<sort-header label="{{d.label}}" index="{{d.index}}" sort-exp="setSort(idx, reverse)"></sort-header>

And, in your controller, you can bind to the sort-exp with a function:

$scope.setSort = function(idx, reverse){
  $scope.sortval = 'columns['+idx+'].value';
  $scope.reverse = reverse;
};

Finally, in your ng-repeat, you can set up your orderBy filter with the scope values that you used to define the sort expression (in this case $scope.sortval) and the sort order (in this case $scope.reverse):

ng-repeat="column in displayData | orderBy: sortval:reverse | filter: query"

if your data is an array then you can use orderBy filter See official doc here : https://docs.angularjs.org/api/ng/filter/orderBy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!