[英]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.