如何使用ng隐藏和ng重复显示基于条件的元素
How to show element based on condition using ng-hide and ng-repeat
我正在使用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)
相关文章:
- 在ng重复循环中显示条件内容的最佳方式是什么
- 使用多个条件筛选ng个重复
- AngularJS:如何使用java脚本函数更改跨度的ng-show条件
- 根据特定条件使用ng显示/ng隐藏来显示/隐藏元素
- 使用ng-hide根据条件显示/隐藏按钮
- AngularJS.Filter in ng中的多个条件重复
- ng重复向一个元素添加条件类
- AngularJS ng-if指令在移除元素之前,即使条件为false,也会短暂呈现
- 角度JS,将过滤条件添加到ng重复
- Angular js ng repeat与条件ng类不应用css类
- 如何在一次有条件的ng单击时执行多个调用
- Ng类条件语法
- 根据条件使用ng repeat动态显示输入复选框
- 为什么不能在带有条件的ng类中使用方法
- 在ng repeat中按条件设置格式/样式
- Angular-使用条件$odd/$even以及ngClass的ng重复属性
- Agularjs ng-class:如果其他条件变为真,则删除类
- 如何在使用 ng-repeat 显示表数据时放置条件新行
- 使用 ng 模型有条件地过滤 ng 选项
- 如何根据条件为 ng-model 赋值