当表没有行时,AngularJS隐藏表

时间:2014-01-05 22:47:03

标签: angularjs html-table

当表没有行时,如何有条件地隐藏HTML表?当我使用过滤器时,我事先不知道结果集是否为空。

我正在迭代表行,但是外表(包括thead)将被渲染,即使没有行也是如此。如何反省结果数组的长度并将该信息用于ng-show / ng-hide?

1 个答案:

答案 0 :(得分:9)

有一些可能的解决方案,但最好的解决方案取决于您的要求和限制。如果它不是一个巨大的应用程序,并且您不希望在未经过滤的数组中包含太多项目,那么最好的解决方案可能只是使用具有相同过滤器的ng-show

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

但请记住,在每个摘要周期中,您的过滤器将在阵列的所有项目中运行两次。如果性能可能有问题,那么您可能希望控制器为您消化此值并将其绑定到您的范围:

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

在你的HTML中:

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