Angular ng-repeat 单选框默认选中第一个

1.多个input的type=”radio”不使用ng-repeat正常获取value值。

<div class="weui-cells weui-cells_radio">
        <label class="weui-cell weui-check__label" for="[[cardFaceNo]]" >
            <div class="weui-cell__bd">
                <p ng-bind="cardFaceNo"></p>
            </div>
            <div class="weui-cell__ft">
                <input type="radio" class="weui-check" name="radio1" id="[[cardFaceNo]]" ng-model="cardRadio" value="123456">
                <span class="weui-icon-checked"></span>
            </div>
        </label>
        <a href="javascript:void(0);" class="weui-cell weui-cell_link" ng-click="toBindCard()">
            <div class="weui-cell__bd"  ng-bind="card" ></div>
        </a>
    </div>

js

$scope.toClaimPrize = function(){
        alert($scope.cardRadio)
    };

2.使用ng-repeat导致无法正确获取value值

html

<div class="weui-cells weui-cells_radio">
        <label class="weui-cell weui-check__label" ng-repeat="cardInfo in userBasicInfo.cardInfoList" for="[[cardInfo.cardFaceNo]]" >
            <div class="weui-cell__bd">
                <p ng-bind="cardInfo.cardFaceNo"></p>
            </div>
            <div class="weui-cell__ft">
                <input type="radio" class="weui-check" name="radio1" id="[[cardInfo.cardFaceNo]]" ng-model="cardRadio" value="[[cardInfo.cardFaceNo]]">
                <span class="weui-icon-checked"></span>
            </div>
        </label>
        <a href="javascript:void(0);" class="weui-cell weui-cell_link" ng-click="toBindCard()">
            <div class="weui-cell__bd"  ng-bind="cardOperation" ></div>
        </a>
    </div>

js

$scope.toClaimPrize = function(){
        alert($scope.cardRadio)
    };

3.问题原因及解决方案

原因:

因为在ng-repeat中,$scope的作用域不是全局的,相当于局部变量,无法在全局访问到其中变量。所以要使用$parent来使其成为全局变量,可全局访问。

解决方案:

若使用ng-repeat则必须在ng-model中加入$parent

示例代码:

<div class="weui-cells weui-cells_radio">
        <label class="weui-cell weui-check__label" ng-repeat="cardInfo in userBasicInfo.cardInfoList" for="[[cardInfo.cardFaceNo]]" >
            <div class="weui-cell__bd">
                <p ng-bind="cardInfo.cardFaceNo"></p>
            </div>
            <div class="weui-cell__ft">
                <input type="radio" class="weui-check" name="radio1" id="[[cardInfo.cardFaceNo]]" ng-model="cardRadio" value="[[cardInfo.cardFaceNo]]  ng-model="$parent.cardRadio" value="[[cardInfo.cardFaceNo]]" ng-checked="$index==0?true:false">
                <span class="weui-icon-checked"></span>
            </div>
        </label>
        <a href="javascript:void(0);" class="weui-cell weui-cell_link" ng-click="toBindCard()">
            <div class="weui-cell__bd"  ng-bind="cardOperation" ></div>
        </a>
    </div>

其中

ng-checked="$index==0?true:false"

是判断第一项单选框是否默认选中。但是也有人说

$index这个东西很危险,不要乱用

不知道是否还有其他方式。

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页