Search code examples
angularjsangularjs-scopeangularjs-filterangularjs-orderby

Angular orderBy and scope


I'm wondering how to properly sort table data when the data is spread accross multiple tables. I have some app data that is displayed in tables based on the country the app belongs to, i.e., each country has its own table of app data. I'm able to sort the table data by clicking the table headings (app properties), using orderBy, but clicking the heading of one of the country tables sorts all of the country tables. I'm wondering how to isolate the scope so that clicking on the table heading of one country's table of app data only changes the order of it's app data and not the other countries tables of app data. I tried adding the countryId property to the app data and then filtering based on the currently clicked country table but that just causes the other country tables to be empty. What's the proper way to isolate the scope of orderBy?

<div class="table-responsive" ng-repeat="countryReleases in regionRelease.countryReleases">
    <h5><strong>{{ countryReleases.countryName }}</strong></h5>
    <table id="app" class="table table-striped table-bordered table-condensed">
        <thead>
            <tr>                    
                <th ng-click="vm.sortCountry = countryReleases.countryId; vm.sortName = 'application.name'; vm.sortReverse = !vm.sortReverse">
                    <span>App Name</span>
                    <span ng-show="vm.sortName == 'application.name' && !vm.sortReverse" class="pull-right fa fa-caret-up"></span>
                    <span ng-show="vm.sortName == 'application.name' && vm.sortReverse" class="pull-right fa fa-caret-down"></span>
                </th>
                <th>App Prop 2</th>
                ...
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="appReleases in countryReleases.appReleases | filter:vm.sortCountry | orderBy:vm.sortName:vm.sortReverse">
                <td>
                    <img class="thumbnail" ng-src="{{ appReleases.application.icon }}">
                    ... 

// Edit: fixed by passing the scope of the current iteration to orderBy filter in the controller:

<th ng-click="vm.sortName = 'application.name'; vm.sortReverse = !vm.sortReverse; vm.orderByAppCountry(this, vm.sortName, vm.sortReverse)">
...

<tr ng-repeat="appReleases in countryReleases.appReleases">
...

  function orderByAppCountry(scope, predicate, reverse) {
    scope.countryReleases.appReleases = $filter('orderBy')(scope.countryReleases.appReleases, predicate, reverse);
  }

Solution

  • Fixed by adding orderBy filter to controller and calling from click of country table, See edit above.