1

我有一个 HTML 表格,如下所示:

<table>
  <tr ng-show="showCats"><td>Cat</td><td>1</td></tr>
  <tr ng-show="showDogs"><td>Dog</td><td>2</td></tr>
  <tr ng-show="showCats"><td>Cat</td><td>4</td></tr>
  <tr ng-show="showDogs"><td>Dog</td><td>3</td></tr>
  <tr ng-show="showCats"><td>Cat</td><td>5</td></tr>
  <tr ng-show="showLizards"><td>Lizard</td><td>1</td></tr>
  <tr ng-show="showLizards"><td>Lizard</td><td>3</td></tr>
  <tr ng-show="showMice"><td>Mouse</td><td>5</td></tr>
  <tr ng-show="showMice"><td>Mouse</td><td>1</td></tr>
  <tr ng-show="showDogs"><td>Dog</td><td>3</td></tr>
</table>

和链接如下:

<a href="#" ng-click="showRows('all')">Show all</a>
<a href="#" ng-click="showRows('cats')">Cats</a>
<a href="#" ng-click="showRows('dogs')">Dogs</a>
<a href="#" ng-click="showRows('lizards')">Lizards</a>
<a href="#" ng-click="showRows('mice')">Mice</a>

单击动物类型时,Angular 中隐藏/显示每一行的正确方法是什么?我知道filter,但我的印象是这只适用于在 Angular 中使用ng-repeat. (此表正在服务器端生成。)

我有一个可行的解决方案,可以showAnimal根据单击的内容手动将每个变量设置为真/假,但这似乎是一种低效、不可扩展的方法。谢谢!

4

1 回答 1

5

鉴于您的限制,您可以执行以下操作:plunker demo

控制器

$scope.selected = 'all';
$scope.isShown = function(animal) {
  if ($scope.selected == 'all') {
    return true;
  }
  return $scope.selected == animal;
}

HTML

<select ng-model="selected">
  <option value="all">All</option>
  <option value="cat">Cat</option>
  <option value="dog">Dog</option>
  <option value="lizard">Lizard</option>
  <option value="mice">Mice</option>
</select>

<table>
  <tr ng-show="isShown('cat')"><td>Cat</td><td>1</td></tr>
  <tr ng-show="isShown('dog')"><td>Dog</td><td>2</td></tr>
  <tr ng-show="isShown('cat')"><td>Cat</td><td>4</td></tr>
  <tr ng-show="isShown('dog')"><td>Dog</td><td>3</td></tr>
  <tr ng-show="isShown('cat')"><td>Cat</td><td>5</td></tr>
  <tr ng-show="isShown('lizard')"><td>Lizard</td><td>1</td></tr>
  <tr ng-show="isShown('lizard')"><td>Lizard</td><td>3</td></tr>
  <tr ng-show="isShown('mice')"><td>Mouse</td><td>5</td></tr>
  <tr ng-show="isShown('mice')"><td>Mouse</td><td>1</td></tr>
  <tr ng-show="isShown('dog')"><td>Dog</td><td>3</td></tr>
</table>
于 2013-08-03T20:42:50.913 回答