glandrum101
glandrum101

Reputation: 466

Why does the ng-repeat directive create a child scope?

Question: Why does the ng-repeat directive create a child scope?

I don't understand why this is the case. Creating a new scope makes sense to an extent if you explicitly create a child controller, but why would it automatically create one for every ng-repeat?

I guess the reason it confuses me is because if you create a loop in JS, that doesn't mean the code outside the loop can't access any of the variables inside of it.

Example:

for(var x=0; x<10; x++) {
   var y = x
}
alert(y);

Upvotes: 1

Views: 663

Answers (3)

craigb
craigb

Reputation: 16907

The DOM is not javascript. The items in the collection you are ng-repeating over need to be bound to separate scopes that are bound to the repeated DOM elements and creates a tree of scopes that mirror structure of the page (somewhat)

ex, this markup:

<body ng-app="myapp">
    <div ng-repeat="item in items">
        <p>{{ item.name }}</p>
    </div>
</body>

will produce something like the DOM on the left and scope on the right:

body            rootScope
    div             scope       
        p
    div             scope
        p

(somewhat approximate for illustration)

Upvotes: 1

Tegan Mulholland
Tegan Mulholland

Reputation: 801

Javascript was written by a single person in 10 days. In almost every other language, loops create a separate scope and your code example wouldn't compile or you'd end up with null/none for y in your last line.

Upvotes: 1

PM 77-1
PM 77-1

Reputation: 13334

From the docs (with my emphasis):

The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and $index is set to the item index or key.

Seems pretty straightforward, doesn't it?

Upvotes: 2

Related Questions