如何使用ng隐藏和ng重复显示基于条件的元素

How to show element based on condition using ng-hide and ng-repeat

本文关键字:ng 条件 元素 于条件 显示 隐藏 何使用      更新时间:2023-09-26

我正在使用AngularJS,我有一个项目表,我希望能够根据它们的颜色显示这些项目。例如,如果我点击"显示绿色"answers"显示红色"复选框,表格将只显示绿色或红色的项目。

这是项目对象:

{"name":"Fire Truck", "color":"red"}

以下是我的复选框,单击后将评估为TRUE或FALSE:

<select id="item_color" ng-model='color'>
   <option value='green'>SHOW GREEN</option>
   <option value='red'>SHOW RED</option>
   <option value='blue'>SHOW BLUE</option>
</select>

这是我的桌子:

<tr ng-repeat="item in items" ng-hide='???'>
   <td>{{item.name}} </td>
   <td>{{item.color}} </td>
</tr>

那么,如何让我的表动态地显示所需的项目呢?理想的解决方案还允许我为每种颜色的所有项目列出3个单独的表格。我不知道该怎么做。有什么想法吗?

<tr ng-repeat="item in items" ng-hide='item.color !== color'>
   <td>{{item.name}} </td>
   <td>{{item.color}} </td>
</tr>

就这么简单。或者,使用ng-if根本不消除反向:

<tr ng-repeat="item in items" ng-if='item.color === color'>
   <td>{{item.name}} </td>
   <td>{{item.color}} </td>
</tr>

感谢Antiga的解决方案。我在ng-hide中使用了类似的控制器功能。这适用于3+条件。

<!-- Checkboxes to toggle T/F which colors to show -->
<input type='checkbox' id='full' ng-model='toggle_red'>RED
<input type='checkbox' id='part' ng-model='toggle_green'>GREEN
<input type='checkbox' id='former' ng-model='toggle_blue'>BLUE
<!-- ng-hide will show item if color_hider() evals to false -->
<tr ng-repeat="item in items" ng-hide='color_hider(item.color)'>
   <td>{{item.name}} </td>
   <td>{{item.color}} </td>
</tr>
<script>
// variables for the toggles
$scope.toggle_red = true;
$scope.toggle_green = true;
$scope.toggle_blue = true; 
// evals to false for each color if both conditions are true
$scope.color_hider(color){
    if(color == 'red' && $scope.toggle_red === true){ 
        return false;
    }else if(color == 'green' && $scope.toggle_green === true){
        return false;
    }else if(color == 'blue' && $scope.toggle_blue === true){
        return false;
    }else{
        return true;
    };
};
</script>

与其在整个集合中重复,然后隐藏单个元素,不如过滤ng-repeat本身:

<tr ng-repeat="item in items | filter:{'color': 'green'}">

将在所有颜色为绿色的项目上重复。

(对于更复杂的条件,您可以使用函数作为过滤器:https://docs.angularjs.org/api/ng/filter/filter)