如何在angularjs中默认选中复选框

时间:2016-06-30 11:25:31

标签: html angularjs checkbox

我希望选中复选框作为默认值。

HTML:

<div class="form-group col-sm-6" ng-class="{ 'has-error': pForm.caddress.$dirty && pForm.caddress.$error.required }">                          
    <label class="control-label l_font" for="address">Current Address*</label>
    <textarea class="form-control" type="text" name="caddress" placeholder="Current address" ng-model="caddress" ng-disabled ="!pEditMode"  ng-required = "true" >
    </textarea>
    <span ng-show="pForm.caddress.$dirty && pForm.caddress.$error.required" class="help-block">Current Address is required</span>                                
</div>


<div class="form-group col-sm-6" ng-class="{ 'has-error': pForm.paddress.$dirty && pForm.paddress.$error.required }">
    <label class="control-label l_font" for="address">Permanent Address*</label>
    <input type="checkbox" ng-model="sameAddrres" ng-checked="copyAddress()" ng-disabled ="!pEditMode" />
    <i class="inside">Select if Permanent address is same as Current address</i>

    <style>
        .inside 
        {
        font-size: 12px;
        }
    </style>
    <textarea class="form-control" type="text" name="paddress" placeholder="Permanent address" 
    ng-model="paddress" ng-disabled ="!pEditMode || sameAddrres" ng-required = "true" ></textarea>
    <span ng-show="pForm.paddress.$dirty && pForm.paddress.$error.required" class="help-block">Permanent Address is required</span>
</div>

如果选中复选框,我正在使用函数将当前地址值复制到永久地址值。

控制器:

$scope.copyAddress = function(){

    if($scope.sameAddrres == true){

        $scope.paddress = $scope.caddress;
    }            
};

2 个答案:

答案 0 :(得分:0)

根据here,您不应该使用ng-checked和ng-checked。 您可以删除ng-chekced并将手表放在此属性上,如下所示:

 $scope.$watchCollection('sameAddrres', function(newValue, oldValue) {
    if(newValue) 
       $scope.paddress = $scope.caddress;
});

答案 1 :(得分:0)

控制器未完成。看起来您已初始化true或未定义。

选中复选框后,根据一个函数将相同的地址字段设置为{{1}},以便在加载控制器时检查两个值是否相同。