Santanu Santanu - 3 months ago 35
AngularJS Question

not getting selected checkbox id along with ng-checked condition in checkboxes in angularjs

I Have a html table which is binding using AngularJs.

<tr class="gradeX" ng-repeat="itm in usersList">
<td>
<input type="checkbox" ng-checked="itm.checkstatus == 1" ng-model="itm.selected" value="{{itm.ID}}" /></td>
<td> {{itm.FirstName}}</td>

<td>{{itm.Email}}</td>

</tr>


During ng-repeat i already add a condition that if itm.chekstatus=1 then checkbox will check otherwise not.But now i want to get all selected checkbox id when a button is clicked.
here is my code for getting the selected checkboxid.

$scope.AddEvent = function (Data) {

debugger
$scope.UserNameArray = [];


angular.forEach($scope.usersList, function (itm) {
if (itm.selected) $scope.UserNameArray.push(itm.ID);
})
var obj = {
idList: $scope.UserNameArray
}
if ($scope.UserNameArray.length > 0) {

$http({
url: "EventRoute/getAllSelectedUserID",
dataType: 'json',
method: 'POST',
data: obj,
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {


}

})
.error(function (error) {
alert(error);
});
}



}


my problem is that when i add a condition ng-checked="itm.checkstatus == 1" along with ng-model="itm.selected" value="{{itm.ID}}" then
i am not getting the selected checkboxid.But when i remove the condition ng-checked="itm.checkstatus == 1" then i am getting the selected checkbox id.
How to do this???

Answer

ngModel and ngChecked are not meant to be used together.

ngChecked is expecting an expression, so by saying ng-checked="true", you're basically saying that the checkbox will always be checked by default. Reference

Actually ng-model selected is doing a action ng checked for you. Instead of adding the directive ng-checked add ng-init (ng-init="itm.selected=itm.checkstatus==1;")

<tr class="gradeX" ng-repeat="itm in usersList" ng-init="itm.selected=itm.checkstatus==1;">
                                <td>
                                    <input type="checkbox" ng-model="itm.selected" value="{{itm.ID}}" /></td>
                                <td> {{itm.FirstName}}</td>

                                <td>{{itm.Email}}</td>

                            </tr>
Comments