1. 程式人生 > >Angular ng-repeat 單選框預設選中第一個

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這個東西很危險,不要亂用

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