Why do angular `ng-repeat` have different flags to differentiate behavior and then list the flag manually?

If I list the checkboxes manually

<ul> <li> <input type="checkbox" ng-model="checkState"/> </li> <li> <input type="checkbox" ng-model="checkState"/> </li> </ul> 

Checking one flag checks all the flags.

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 flag checks only one of them

Is there a reason for this? From the DOM, they both look the same.

+6
source share
2 answers

The problem is related to angular scope . Each angular application has one root area by default. However, it may have several child areas.

Some built-in directives create new child areas. ng-repeat is an example of this. Each element within this directive has its own scope. When these areas are created, they are automatically added as children of the parent area.

This creates a tree structure similar to the DOM

 rootScope - childScope - childScope - childScope 

Check your HTML browser to see this in action. 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> 

Note that each ng-repeat element has an ng-scope and ng-binding class.

The directive instantiates a template once for an element from the collection. Each element of the template, in this case, each element li has its own region.

The directive uses $watchCollection to detect changes to the collection. ng-repeat makes the following changes to the DOM

  • When a new element is added, a new instance of the template is added to the DOM
  • When an item is deleted, its template instance is removed from the DOM
  • When elements are reordered, their templates are reordered using the DOM

Here is the official documentation for Angular

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

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

+1
source

In the ng-repeat example, although all models have the same name, each of them is associated with a different area.

See the AngularJS Developer's Guide - Scope for more information.

+1
source

All Articles