AngularJS hide table when table has no rows

How can I conditionally hide an HTML table when there are no rows in the table? Since I use filters, I do not know in advance whether the result set will be empty or not.

I repeat the rows of the table, but the outer table (including thead) will be displayed even if there are no rows. How can I inherit the length of the resulting array and use this information for ng-show / ng-hide?

+4
source share
1 answer

There are several possible solutions, but the best one will depend on your requirements and limitations. If this is not a huge application, and you do not expect to have too many elements in your unfiltered array, the best solution would probably be to just use ng-showwith the same filter:

<table ng-show="(items | filter:criteria).length">
  <tr ng-repeat="item in items | filter:criteria">...</tr>
</table>

But keep in mind that your filter will go through all the elements of the array twice, in each digest cycle. And if performance can be a problem, then you probably want your controller to digest this value for you and just bind it to your area:

controller('YourCtrl', function($scope, $filter) {
  // $watchCollection available in version 1.1+
  $scope.$watchCollection('items', function(newVal) {
    $scope.filteredItems = $filter('filter')(newVal, $scope.criteria);
  });
});

And in your HTML:

<table ng-show="filteredItems.length">
  <tr ng-repeat="item in filteredItems">...</tr>
</table>
+8
source

All Articles