【问题标题】:how to make checkbox checked by default in angularjs如何在angularjs中默认选中复选框
【发布时间】:2016-08-04 17:05:51
【问题描述】:

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

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;
    }            
};

【问题讨论】:

    标签: html angularjs checkbox


    【解决方案1】:

    控制器不完整。看起来你已经初始化了$scope.sameAddress = false 或者没有定义。

    选中复选框时,根据加载控制器时检查两个值是否相同的函数,将sameAddress 字段设置为true

    【讨论】:

    • 但在控制器中我使用了一个条件 if($scope.sameAddrres == true)
    • 当我选中复选框时,当前地址字段的值将复制到永久地址字段。我将所有值存储在后端并在页面刷新或再次登录时获得响应。但是当我刷新页面时,复选框消失了,因此该字段被启用。所以你能帮我解决我犯错的地方吗?
    • Refresh 正在销毁旧值并创建一个新的控制器实例。因此,以前的值会丢失。在控制器渲染页面后,检查两个字段的值,如果相等,将输入复选框模式设置为true,默认为false。
    【解决方案2】:

    根据here,您不应该使用带有 ng-checked 的 ng-model。 您可以像这样删除 ng-chekced 并将监视放在此属性上:

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

    【讨论】:

      猜你喜欢
      • 2015-02-01
      • 2016-09-03
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多