user1219626
user1219626

Reputation:

Why in Angularjs on selecting one checkbox, all checbox getting selected?

Hey guyz i am having issue related to checkboxes in html, i am using angularjs. Whenever i checked one checkbox other checkbox getting selected and vice-versa. Here's my Html code.

<form ng-show='MyForm'>
<div ng-controller="MyController">
<div name="sampleName"  ng-repeat="sample in list" >
 <input ng-model="q.sample" type="checkbox" >{{sample.name}}</label>
</div>
</div>
 <button ng-click="submitForm()" >Submit</button>
 <button ng-click="cancelForm()">Cancel</button>
</form>

But instead of using scope variable name 'q.sample', if i use only $scope.sample then it is working fine. Still there is another issue with this too, On submitting data my form gets closed, but when i open it again, it shows me fresh form, there is no checked field, but if i cancel the form instead of submitting it with checked values and again opened it , i dont want the checked values to be present but i am getting the checked values instead of fresh form. I tried to make values false in checkbox field on cancel button . See my Code of cancelForm()

$scope.cancelForm = function() {
    $scope.MyForm = false
    $scope.q.sample = false
}

So Basically, i have two questions, one is why i am getting all checkboxes selected on selected only one checkbox when i am using

$scope.q.sample

Second when i am using only

$scope.sample

scope value of sample is not reflecting on UI though it is reflecting in JS, i am getting the checked checkboxes.

Upvotes: 0

Views: 3996

Answers (2)

rmuller
rmuller

Reputation: 1837

Indeed as David Tryon mentioned, you are assigning the same ng-model to all the checkboxes and what you want is a different ng-model for each checkbox.

You can solve this by assigning a javascript expression to ng-model

for example:

ng-model="list[$index].checked"

Upvotes: 0

Davin Tryon
Davin Tryon

Reputation: 67316

It is because you are binding ng-model to the same controller property with this:

ng-model="q.sample"

Instead, if you want to select each individually then you need to have a different ng-model for each checkbox.

At the moment, you are changing q.sample and this, then, binds the value of q.sample to all the other checkboxes that define ng-model="q.sample".

Try something like this instead:

<div name="sampleName"  ng-repeat="item in list" >
    <input ng-model="item.checked" type="checkbox" >{{sample.name}}</label>
</div>

and then in cancelForm():

$scope.cancelForm = function() {
    $scope.MyForm = false

    angular.forEach($scope.list, function(item) {
        item.checked = false;
    });
}

Upvotes: 2

Related Questions