Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why angular `ng-repeat` have different checkbox differentiate behavior then listing out checkbox manually?

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.

like image 235
testing Avatar asked Mar 03 '16 01:03

testing


2 Answers

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

  • When a new item is added, a new instance of the template is added to the DOM
  • When an item is removed, its template instance is removed from the DOM
  • When items are reordered, their templates are reordered by the DOM

Here's the official documentation for Angular

https://docs.angularjs.org/api/ng/directive/ngRepeat

https://docs.angularjs.org/guide/scope

like image 75
Richard Hamilton Avatar answered Oct 24 '22 18:10

Richard Hamilton


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

like image 45
georgeawg Avatar answered Oct 24 '22 17:10

georgeawg