Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS hide table when table has no rows

How can I conditionally hide a HTML table, when the table has no rows? As I am using filters, I do not know beforehand if the result set will be empty or not.

I am iterating over the table rows, but the outer table (including the thead) will get rendered, even if there are no rows. How can I introspect into the length of the resulting array and use that information for ng-show / ng-hide?

like image 226
JohnDoe Avatar asked Jan 05 '14 22:01

JohnDoe


1 Answers

There are some possible solutions, but the best one would depend on your requirements and restrictions. If it's not a huge application, and you don't expect to have too many items in your unfiltered array, the best solution would be probably to simply use a ng-show with 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 run through all items of the array twice, on every digest cycle. And if performance might be a problem, then you probably want your controller to digest this value for you and just bind it to your scope:

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>
like image 136
Caio Cunha Avatar answered Sep 30 '22 09:09

Caio Cunha