Angular Get Selected CheckBoxes

孤人 提交于 2019-11-30 22:06:58

问题


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?


回答1:


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



回答2:


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"




回答3:


<tr ng-repeat="x in numbers" >
<td><input type="checkbox"  ng-model="selected[x.id]"></td>`<tr ng-repeat="x in numbers" >

then button for action

 <button ng-click="get_all_cheked()">Get checked</button>    

and then in controller

 $scope.selected = {};
 $scope.get_all_cheked=function () {
 console.log("click");
 console.log($scope.selected);
 }


来源:https://stackoverflow.com/questions/18100629/angular-get-selected-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!