5

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?

2

1 Answer 1

10

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>
Sign up to request clarification or add additional context in comments.

6 Comments

This is a good answer, specifically the suggestion about doing the filtering in the controller.
I put my controller here jsfiddle.net/jaL6b/1 and included your solution. But the watchcollection doesn't get called. Using angular 1.2.6
Ok, another try. See jsfiddle.net/jaL6b/2 : I now register the filter function properly and it get's called. The only strange thing I notice is, that the filter function get's called for every item in the collection, instead of the whole collection. I thought that this filter function is supposed to return the filtered array.
The fiddles are not working, they have invalid JS code, maybe you changed it?
@CaioToOn I am having difficulties in creating a MWE, the stuff is just to new (for me). But the filter receives only one element instead of the array. As such it can not return (and set) the array as you suggested.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.