【问题标题】:Set class to checked radio-button in angular?将类设置为角度中的选中单选按钮?
【发布时间】:2013-10-01 00:41:42
【问题描述】:

我正在使用 ng-repeat 生成一堆单选按钮。

<div class="radiobutton" ng-repeat="mylabel in field.labels">
    <input
        type="radio" 
        name="{{field['key']}}"
        value="{{mylabel.label}}" 
        id="{{mylabel.name}}"

    >
    <label for="{{field['key']}}">
        {{mylabel.label}}
    </label>
</div>

我想根据输入元素是否被检查,使用角度向输入元素添加一个类。据我所知,我应该将一个 ng-model 应用于元素,然后使用它来声明一个 ng-class,但是我该如何制作它以便每个输入都有它自己的模型名称?

【问题讨论】:

  • 所有收音机都属于同一类吗? .active 之类的东西?

标签: angularjs


【解决方案1】:

尝试:

<div class="radiobutton" ng-repeat="mylabel in field.labels">
    <input
        type="radio" 
        name="{{field['key']}}"
        value="{{mylabel.label}}" 
        id="{{mylabel.name}}"
        ng-model='$parent.my_radio_button'
        ng-class='{ class_name: (my_radio_button == mylabel.label) }'
    >
    <label for="{{field['key']}}">
        {{mylabel.label}}
    </label>
</div>

由于您使用单选按钮,我猜只能选择一个,因此您可以共享相同的ng模型。

【讨论】:

  • Hrm I would have thoutght that they needed different models, because when one of the objects were selected all would share the same value, but the == mylabel.label-thing was really smart.这适用于选择按钮,但不适用于取消选择它们,例如 ng-click。
  • 我确认您的所有单选按钮只需要一个 ng 模型,实际上这就是单选按钮的定义:许多选项,一个可能的值
  • 是的,当我单击另一个单选按钮时,模型似乎没有更新。两者都变为真值...我尝试了 ng_class='my_radio_button' 这证实了我的怀疑。
  • 当循环创建新范围时,我必须添加 $parent。到模型。现在可以了!
猜你喜欢
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多