繁体   English   中英

如何使用ng-hide和ng-repeat根据条件显示元素

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

我正在使用AngularJS,并且有一个要根据其颜色显示的项目表。 例如,如果我单击“ SHOW GREEN”和“ SHOW RED”复选框,该表将仅显示绿色或红色的项目。

这是item对象:

{"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重复然后隐藏单个元素,不如对ng-repeat本身进行过滤可能会更好:

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

将对所有颜色为绿色的项目进行ng-repeat。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM