AngularJS按条件显示/隐藏单选按钮组的实现问题
解决方案:根据食物类型动态控制尺寸单选按钮的显示
看起来你之前的实现逻辑没抓准核心需求——我们需要分别控制尺寸选择组的整体显示和单个尺寸按钮的显示,而不是只做一层判断。下面一步步帮你修正:
1. 修正控制器中的显示判断逻辑
首先,先确保尺寸选择组只在需要的场景下显示(比如用户选了vegetarian或nonvegetarian时才显示,选vegan时隐藏),同时为单个按钮的显示准备判断逻辑:
// 控制器内的代码 this.foodSizeChoice = () => { // 仅当选中vegetarian或nonvegetarian时,显示尺寸选择组 return ['vegetarian', 'nonvegetarian'].includes(this.model.foodType); }; // 可选:封装单个尺寸按钮的显示判断,让HTML更简洁 this.canShowSizeOption = (size) => { const selectedFoodType = this.model.foodType; switch(size) { case 'small': // small在两种需要显示尺寸的场景下都可见 return ['vegetarian', 'nonvegetarian'].includes(selectedFoodType); case 'medium': // medium仅在选nonvegetarian时可见 return selectedFoodType === 'nonvegetarian'; default: // large按钮按需求始终隐藏 return false; } };
2. 修改尺寸选择组的HTML代码
接下来给每个尺寸单选按钮加上单独的显示控制,确保符合你的需求:
<div class="sys-form__field" ng-show="booking.foodSizeChoice()" layout="row"> <!-- 选vegetarian/nonvegetarian时都显示small --> <input type="radio" ng-model="booking.model.foodSize" value="small" title="" ng-show="booking.canShowSizeOption('small')" > Small <!-- 仅选nonvegetarian时显示medium --> <input type="radio" ng-model="booking.model.foodSize" value="medium" title="" ng-show="booking.canShowSizeOption('medium')" > Medium <!-- large按钮按需求隐藏 --> <input type="radio" ng-model="booking.model.foodSize" value="large" title="" ng-show="booking.canShowSizeOption('large')" > Large </div>
简化版(不用封装函数)
如果你觉得封装函数有点麻烦,也可以直接在HTML里写表达式,效果是一样的:
<div class="sys-form__field" ng-show="['vegetarian', 'nonvegetarian'].includes(booking.model.foodType)" layout="row"> <input type="radio" ng-model="booking.model.foodSize" value="small" title=""> Small <input type="radio" ng-model="booking.model.foodSize" value="medium" title="" ng-show="booking.model.foodType === 'nonvegetarian'" > Medium <input type="radio" ng-model="booking.model.foodSize" value="large" title="" ng-show="false"> Large </div>
这样修改后,就能精准实现你的需求:选vegetarian只显示small,选nonvegetarian显示small和medium,选vegan时整个尺寸组隐藏。
内容的提问来源于stack exchange,提问作者venura
相关产品推荐
相关产品推荐

