【问题标题】:How to make checked attribute work with intermediate option?如何使选中的属性与中间选项一起使用?
【发布时间】:2023-03-09 09:00:01
【问题描述】:

我有一组日期、月份和年份的单选按钮。

<label>
   <input type="radio" ng-model="IsDays" name="timeunit" > Period in days
   <input type="radio" ng-model="IsMonths" ng-checked="true" name="timeunit"> Period in months
   <input type="radio" ng-model="IsYears" name="timeunit" > Period in years
</label>


我已经读到尽管将选中的属性设置为中间选项,组中的最后一个按钮将被选中,如果单选按钮具有相同的名称属性值

我在 checkedng-checked="true" 两种情况下都试过这个。

是否有一种简单的方法可以覆盖此行为并允许默认检查中间选项(month)?

更新:解决了我自己的问题。请参阅下面的答案。

【问题讨论】:

    标签: html angularjs


    【解决方案1】:

    发布答案以供将来参考:

    Just checked 仅在需要默认选中最后一个单选按钮选项时才有效。

    我们需要提供 checked="checked" 以使其适用于中间选项。在这种情况下,仅 选中 将不起作用。

    <label>
     <input type="radio" ng-model="IsDays" name="timeunit" > Period in days
     <input type="radio" ng-model="IsMonths" checked="checked" name="timeunit"> Period in months
     <input type="radio" ng-model="IsYears" name="timeunit" > Period in years
    

    奇怪:)

    更新:即使在清除浏览器 cookie 后这也不起作用。在查看了一些 AngularJS 文档后,我得到了以下解决方案。

            <label>
                <input type="radio" ng-model="timeunit" value="days">
                Period in days
            </label><br />
            <label>
                <input type="radio" ng-model="timeunit" value="months">
                Period in months
            </label><br />
            <label>
                <input type="radio" ng-model="timeunit" value="years">
                Period in years
            </label><br />
    

    我们必须为所有三个单选按钮的 ng-model 设置相同的值,而不是设置相同的名称属性,以使它们作为一个组起作用。

    要设置默认,我们可以在js文件中设置如下

     function ($scope) {
    
        $scope.timeunit = "months"; //Default set to months
    
      //Other code
     }
    

    【讨论】:

      【解决方案2】:

      您可以使用ngInit 来做到这一点 喜欢:

      <input type="radio" ng-model="IsMonths" ng-init="checked=true" name="timeunit"> Period in months
      

      【讨论】:

      • 更新的解决方案@Rahul
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多