如何存储checkbox true / false的结果

时间:2017-07-14 10:59:25

标签: javascript angularjs checkbox

我已经加载了默认选中的复选框。如果用户取消选中它,则应存储它的值。怎么做? 在这里,我已经检查了所有元素的代码。

$scope.isAllRecordSelected = function(record) {
  var checked = false;
  for (var i = 0; i < $scope.users.length; i++) {
    if (record === $scope.users[i]) {
      checked = true;

      $scope.users[i].selected = checked;
    }


  }
  return checked;
};

html:

<div ng-repeat="record in users">
  <div class="col-md-2 col-sm-2 col-xs-2">
    <label>
      <input type="checkbox" ng-model="isAllSelected"                          
              ng-change="userSelectedToggle()"             
              ng-checked="isAllRecordSelected(record)">             
    </label>
  </div>
  <div class="col-md-6 col-sm-6 col-xs-6">
    <div class="text-overflow">
      <span ng-model="record.dispalyName">  
             {{record.displayName}}</span>
    </div>
  </div>
  <div class="col-md-4 col-sm-4 col-xs-4">
    <span ng-model="record.mobile">  {{record.mobile}}</span>
  </div>
</div>                                   

1 个答案:

答案 0 :(得分:1)

您的用户数组中已有一个名为selected的密钥,用于跟踪已选中/未选中的值。默认情况下,您必须在页面加载时调用isAllRecordSelected(),以便检查每个复选框。现在,您可以根据选择键保持已选中/未选中复选框的计数。

<强> HTML

 <div ng-repeat="record in users">
  <div class="col-md-2 col-sm-2 col-xs-2">
    <label>
      <input type="checkbox" ng-model="isAllSelected"                          
              ng-change="userSelectedToggle($index)"             
              ng-checked="record.selected ">             
    </label>
  </div>
  <div class="col-md-6 col-sm-6 col-xs-6">
    <div class="text-overflow">
      <span ng-model="record.dispalyName">  
             {{record.displayName}}</span>
    </div>
  </div>
  <div class="col-md-4 col-sm-4 col-xs-4">
    <span ng-model="record.mobile">  {{record.mobile}}</span>
  </div>
</div>   

JS

$scope.isAllRecordSelected = function() {
    for (var i = 0; i < $scope.users.length; i++) {
        $scope.users[i].selected = true;
    }
}
$scope.userSelectedToggle = function(index) {
    if ($scope.users[index].selected)
        $scope.users[index].selected = false;
    else
        $scope.users[index].selected = true;
}
$scope.isAllRecordSelected();//initialise all checkbox as checked