Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Get Selected CheckBoxes

I have a list of dynamically filled checkboxes using angular.

 <div ng-repeat="X in XList">
     <label>{{X.Header}}</label>
     <input type="checkbox" name="X" value="{{X.Item.Id}}" />
     <p>{{X.Header}}</p>
 </div>

I want a method to retrieve a list of all the selected checkboxes. Usually I'd use

 $('input[name=checkboxlist]:checked').each(function()
{
}

But this is not acceptable with angular .... So is there an appropriate Method to do so?

like image 976
Sana Joseph Avatar asked Aug 07 '13 10:08

Sana Joseph


People also ask

How do I check if a checkbox is checked in angular 8?

The ng-checked Directive in AngularJS is used to read the checked or unchecked state of the checkbox or radio button to true or false. If the expression inside the ng-checked attribute returns true then the checkbox/radio button will be checked otherwise it will be unchecked.


2 Answers

here is the implemented plunker

 <input type="checkbox" ng-model="selected[record.Id]"> {{record.Id}}

 $scope.ShowSelected = function() {
  console.log($scope.selected);
  alert(JSON.stringify($scope.selected));
};
like image 126
Vinod Louis Avatar answered Oct 09 '22 16:10

Vinod Louis


You can use the ng-model directive to directly bind a property to the element.

e.g.

<input type="checkbox" ng-model="X.Item.Id" />

This will update your model.

From this you will be able just to check the values within your model and see which are checked.

e.g.

angular.forEach($scope.yourModelItems, function(item){
    // item.value ? 0 : 1;
});

Check out the documentation for ngModel. Also the ToDo list example on the angularjs.org homepage demonstrates this.

p.s. On a side note, you can also make your angular directives html5 friendly by adding data- before. e.g. data-ng-model="X.Item.Id"

like image 1
Tim B James Avatar answered Oct 09 '22 18:10

Tim B James