If I list out checkboxes manually
<ul>
<li>
<input type="checkbox" ng-model="checkState"/>
</li>
<li>
<input type="checkbox" ng-model="checkState"/>
</li>
</ul>
Checking one checkbox checks all of the checkbox.
But if I use ng-repeat
<div>
<ul>
<li ng-repeat="elem in someArray">
<input type="checkbox" ng-model="checkState" />
</li>
</ul>
</div>
Checking one checkbox only checks one of them
Is there a reason for this? From the DOM they both looks the same.
The issue relates to the angular's scope
. Each angular application has by default one root scope. It can however have multiple child scopes.
Some built in directives create new child scopes. ng-repeat
is an example of this. Every element inside this directive has its own scope. When these scopes are created, they are automatically added as children of the parent scope.
This creates a tree structure similar to the DOM
rootScope
- childScope
- childScope
- childScope
To see this in action, check out your browser's HTML. It will look something like this
<div>
<li ng-repeat="elem in someArray" class="ng-scope ng-binding">elem 1
<input type="checkbox" ng-model="checkState" />
</li>
<li ng-repeat="elem in someArray" class="ng-scope ng-binding">elem 1
<input type="checkbox" ng-model="checkState" />
</li>
</div>
Notice that each ng-repeat element has an ng-scope
and an ng-binding
class.
The directive instantiates a template once per item from a collection. Every template item, in this case every
li
element has its own scope.
The directive uses $watchCollection
to detect changes in the collection. ng-repeat makes the following changes to the DOM
Here's the official documentation for Angular
https://docs.angularjs.org/api/ng/directive/ngRepeat
https://docs.angularjs.org/guide/scope
In the ng-repeat
example, even though the models all have the same name, they are each bound to a different scope.
For more information, see AngularJS Developer Guide - Scope
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With