You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS点击单选按钮移除hide类显示另一组单选按钮求助

解决AngularJS单选按钮选中后显示另一组ng-repeat内容的问题

哈哈我太懂这种搜了半天还卡壳的崩溃感了!咱们直接上解决方案,一步步搞定这个需求~

核心思路

  1. 用一个变量存储用户选中的第一组单选按钮数据,比如selectedDrink
  2. 通过这个变量的状态来控制第二组内容的显示/隐藏(移除hide类)
  3. 两组内容都用ng-repeat渲染,保持数据驱动的逻辑

完整代码示例

HTML部分

<div ng-app="drinkApp" ng-controller="DrinkController">
  <!-- 第一组饮品单选按钮 -->
  <div class="primary-drinks">
    <label ng-repeat="drink in primaryDrinks">
      <input type="radio" ng-model="selectedDrink" ng-value="drink" />
      {{drink.name}} - ${{drink.price.toFixed(2)}}
    </label>
  </div>

  <!-- 第二组联动显示的单选按钮,默认隐藏 -->
  <div class="secondary-drinks" ng-class="{'hide': !selectedDrink}">
    <p>选择额外选项:</p>
    <label ng-repeat="option in secondaryOptions">
      <input type="radio" ng-model="selectedOption" ng-value="option" />
      {{option.name}} - ${{option.price.toFixed(2)}}
    </label>
  </div>
</div>

CSS部分(定义hide类)

.hide {
  display: none;
}

AngularJS控制器部分

angular.module('drinkApp', [])
.controller('DrinkController', function($scope) {
  // 第一组饮品数据
  $scope.primaryDrinks = [
    {name: '拿铁', price: 2.00},
    {name: '美式', price: 1.50},
    {name: '卡布奇诺', price: 2.20}
  ];
  
  // 第二组联动选项数据(如果需要和主饮品关联,可以加过滤逻辑)
  $scope.secondaryOptions = [
    {name: '双倍浓缩', price: 0.50},
    {name: '香草糖浆', price: 0.60},
    {name: '脱脂奶', price: 0.30}
  ];
  
  // 存储选中的主饮品,初始为空
  $scope.selectedDrink = null;
  $scope.selectedOption = null;
});

关键细节解释

  • 单选按钮绑定:第一组的ng-model="selectedDrink"会把选中的饮品对象直接存到这个变量里,ng-value="drink"确保绑定的是完整的对象(而不是字符串)
  • 显示控制:第二组容器的ng-class="{'hide': !selectedDrink}"是核心——当selectedDrink为空(未选中任何主饮品)时,添加hide类隐藏;一旦选中主饮品,selectedDrink有值,hide类自动移除,内容就显示出来了
  • 进阶扩展:如果第二组选项需要和选中的主饮品关联(比如不同饮品对应不同选项),可以给主饮品加optionIds字段,然后用过滤器:ng-repeat="option in secondaryOptions | filter: {id: selectedDrink.optionIds}"

内容的提问来源于stack exchange,提问作者Reena Verma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:49:18