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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With