0

There seems to be a problem with the ngModel.

I'm trying to get the selected checkbox IDs but it's not saving because their checked property isn't changed by the ngModel.

These are only partial code snippets. When I turned one of the checked values into true, the ID saved into the checkbox array (addCustom function runs when a button is clicked).

How do I fix this so that I could get the selected checkboxes?

$scope.checkboxData = [{
  name: "Computer Crash",
  id: 1,
  checked: false
}, {
  name: "Computer Restart",
  id: 2,
  checked: false
}];


$scope.addCustom = function() {
  $scope.custom = !$scope.custom; // close modal

  // get checkbox id
  $scope.checkboxArray = [];

  $scope.checkboxData.forEach(function(checkbox) {
    if (checkbox.checked) {
      console.log(checkbox.id);
      $scope.checkboxArray.push(checkbox.id);
    }
  })
  console.log($scope.checkboxArray);

  //////

  $scope.data.push({
    name: $scope.name,
    symptom: $scope.checkboxArray,
    answer: $scope.answer
  });
  localStorage.setItem('data', JSON.stringify($scope.data));
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<div ng-app="Netsafe" ng-controller="activityController">
  <div ng-repeat="checkbox in checkboxData" class="form-check form-check-inline col-sm-4">
    <label>
      <input type="checkbox" ng-model="checkbox.checked"/>
      {{checkbox.name}}
    </label>
  </div>
</div>
hasan
  • 3,484
  • 1
  • 16
  • 23
Macaronie
  • 31
  • 3
  • It's a common problem with ng-repeat, have you tried to print directly some checkboxes? – Sampgun Jun 10 '17 at 11:28
  • As far as model binding goes, your code seems to be working fine. The checkbox's checked state is getting bound to the model properly. Here is a working plunker: https://plnkr.co/edit/1rWluY3HTh861ndZ1Ogt?p=preview – CodeWarrior Jun 10 '17 at 11:36
  • 1
    The basics of your code work fine here http://plnkr.co/edit/bCQ74Dw4rAqklDAn28DH?p=preview – charlietfl Jun 10 '17 at 11:40
  • Idem http://jsfiddle.net/tonysamperi/rg8h3238/ – Sampgun Jun 10 '17 at 11:43

0 Answers0