Questions And Answers

More Tutorials

Angular The $scope tree

The previous example is good enough when we need to bind a single html element, to a single variable.In reality - we need to bind many elements to many variables:

<span ng-repeat="number in [1,2,3,4,5]">{{number}}</span>

This ng-repeat binds 5 elements to 5 variables called number, with a different value for each of them!

The way angular achieves this behavior is using a separate context for each element which needs separate variables. This context is called a scope.

Each scope contains properties, which are the variables bound to the DOM, and the $digest and $watch functions are implemented as methods of the scope.

The DOM is a tree, and variables need to be used in different levels of the tree:

 <input ng-model="" />
 <span ng-repeat="number in [1,2,3,4,5]">{{number}} {{}}</span>

But as we saw, the context(or scope) of variables inside ng-repeat is different to the context above it. To solve this angular implements scopes as a tree.

Each scope has an array of children, and calling its $digest method will run all of its children's $digest method.

This way - after changing the input - $digest is called for the div's scope, which then runs the $digest for its 5 children - which will update its content.

A simple implementation for a scope, could look like this:

function $scope(){
 this.$children = [];
 this.$watches = [];
$scope.prototype.$digest = function(){
 var val = $w.val();
 if($w.prevVal !== val){
 $w.callback(val, $w.prevVal);
 $w.prevVal = val;
$scope.prototype.$watch = function(val, callback){
 this.$watches.push({val:val, callback:callback, prevVal: val() })

note: this is example is a demonstration, not the actual angular code


In this page (written and validated by ) you learned about AngularJS The scope tree . What's Next? If you are interested in completing AngularJS tutorial, your next topic will be learning about: AngularJS scopes.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.