user818700
user818700

Reputation:

Having some difficulty working with checkboxes in AngularJS

I have list that gets filled up with 'allergies' that it fetches from a web service. So allergies could look something like this:

$scope.formData.allergies = [
  {
    'id' : 1, 
    'description' : 'Potassium Cyanide'
  },
  {
    'id' : 2, 
    'description' : 'Blue ring octopus'
  },
  {
    'id' : 3, 
    'description' : 'Poison dart frog'
  },
];

Which then gets used to populate a list of checkbox inputs:

 <li class="item item-checkbox" ng-repeat="allergy in formData.allergies">
   <label class="checkbox">
     <input type="checkbox" name="selectedAllergies" value="allergy.id">
   </label>
   {{allergy.description | uppercase}}
 </li>

But I'm struggling on how to find out what the user actually selected? Doing this after the user selected a few:

console.log($scope.selectedAllergies);

just returns undefined...

Upvotes: 0

Views: 40

Answers (2)

Dhanush Gopinath
Dhanush Gopinath

Reputation: 5739

You need to add an ng-model to the <input> element to do the binding

<input ng-model="allergy.checked" type="checkbox"> 

And then initialise it in the controller like this

$scope.formData.allergies = [
  {
    'id' : 1, 
    'description' : 'Potassium Cyanide',
     'checked' : false
  },
  {
    'id' : 2, 
    'description' : 'Blue ring octopus',
     'checked' : false
  },
  {
    'id' : 3, 
    'description' : 'Poison dart frog',
     'checked' : false
  },
];

Initially all of them will be in un-checked state and when the user selects a check box, say the first one, the value of $scope.formData.allergies[0].checked will be true

Upvotes: 0

Aaron
Aaron

Reputation: 24802

Your checkbox input has a value (what it will set the model to) but no ng-model, so it doesn't know what to do with this value.

I think the easiest would be to modify the allergies array, so you could have the following code :

<li class="item item-checkbox" ng-repeat="allergy in formData.allergies">
    <label class="checkbox">
        <input type="checkbox" name="selectedAllergies" ng-model="allergy.selected">
    </label>
    {{allergy.description | uppercase}}
</li>

Without any value the allergy.selected should be set to a truthey or falsey value depending on the checkbox state.

Upvotes: 1

Related Questions