Angularjs scope detailed and sample code _ANGULARJS

Source: Internet
Author: User
Tags assert emit

One, what is scope?

Scope (http://code.angularjs.org/1.0.2/docs/api/ng. $rootScope. Scope) is an object that points to application model. It is also the execution context of expression (http://www.cnblogs.com/lcllao/archive/2012/09/16/2687162.html). Scope is placed in a hierarchical structure of a similar application DOM structure. Scope can monitor (watch, $watch) expression and propagate events.

Ii. Characteristics of scope

    1. Scope provides the $watch API (http://code.angularjs.org/1.0.2/docs/api/ng. $rootScope. scope# $watch) for monitoring model changes.
    2. Scope provides $apply APIs (http://code.angularjs.org/1.0.2/docs/api/ng. $rootScope. scope# $apply), in "Angular realm" (Controller, server, angular event handler), propagate any model changes from system to view.
    3. Scope can be embedded in a stand-alone application component when it provides access to the shared model property. Scope passes (prototypes) and inherits attributes from parent scope.
    4. Scope provides a context when expression is evaluated. For example, the {{username}} expression is meaningless unless it is evaluated with a specific scope that defines the "username" property.

Iii. Scope as Data-model (scope as data model)

Scope is the link between applying controller and view. In the stage of template linking (http://www.cnblogs.com/lcllao/archive/2012/09/04/2669802.html), Directive (http://www.cnblogs.com/ lcllao/archive/2012/09/09/2677190.html) Sets the $watch expression in scope. $watch allows directive to learn about the changes in properties, allowing directive to render the updated value to the DOM.

Both controller and directive have references to scope, but there is no (reference) between them (Both controllers and directives have to the scope, reference not to EAC h other). This arrangement separates the Controller from the directive and the DOM. This is an important place because it allows controller to be isolated from view, greatly enhancing the testability of the application (greatly improves the testing story of the applications).

<! DOCTYPE html>

In the above example, we can note that Mycontroller assigns the username attribute in scope with "My Little Dada". Next, the scope notifies input to assign the value, username the value to the input. This shows how controller can write data into scope.

Similarly, controller can attach behavior to scope, just as the SayHello method triggers when the user clicks the Welcome button. The SayHello method can either read the Username property or create the Greeting property. This means that when they are bound to an HTML input control, the properties in scope are automatically updated.

Logically, the display of {{greeting}}} involves the following two points:

Retrieves a scope with the template DOM node that defines the {{greeting}} expression. In this case, this scope is the same as the scope passed into the Mycontroller. (We'll discuss the hierarchy of scope later)
Evaluates the greeting expression by the scope previously retrieved, and then takes the result as the value of the text of the enclosing DOM element.

We can assume that scope and its own properties can be used as data for rendering views. Scope is a single source of truth about all the view-related things (the scope is the unique source-of-truth for all things View related).

In terms of testability, the separation of controller and view is gratifying, as it allows us to test behavior without the distraction of the details of the rendering.

It (' Should say hello ', function () {
 var scopemock = {};
 var cntl = new Mycontroller (scopemock);
 
 Assert that username are pre-filled
 expect (scopemock.username). Toequal (' World ');
 
 Assert that we read new username and greet
 scopemock.username = ' angular ';
 Scopemock.sayhello ();
 Expect (scopemock.greeting). Toequal (' Hello angular! ');
});

Iv. Scope hierarchies (scope hierarchy)

Each angular application has and only one root scope, but can have multiple child scopes.

Applications can have multiple child scopes because some directive create a new child scope (refer to the directive document to see which directive can create a new scope, such as Ng-repeat). When the new scope is created, they are added to the parent scope as a child scope. This creates a tree structure similar to the DOM that they are attached to.

When angular is evaluated on {{username}}, it first looks at the Username property of the scope associated with the current element. If the corresponding attribute is not found, it will search the parent scope up until it reaches root scope. In JavaScript, this behavior is referred to as "prototype inheritance," where child scope is typically inherited from their parent.

This example shows the scope of the application (how it is), and the prototype inheritance of the attribute.

 <! DOCTYPE html>  
 

Note that angular automatically places the Ng-scope class into the element that is glued to the scope. <style> definition in the above example, the new scope is highlighted by a dashed red line. Because repeater evaluates to {{employee.name}}}, child scope is required, but depending on which scope the expression evaluates, different scopes have different results. Similarly, the value of {{department}} is inherited from the root scope Zhongyuan type, and only in that place is the definition of the Department attribute.

V. Retrieving scopes from the DOM (retrieve scope from DOM)

Scope is attached to the DOM as a $scope data attribute and can be used for retrieval as a purpose for debugging purposes. (It is not possible to retrieve scope in this way in an application.) The location of the root scope of the DOM attached to is defined by the location of the Ng-app directive. Usually Ng-app is placed in the

View Scope in debugger:

1. In the browser, right click on the element of interest and select "View Element". We can see the browser debugger highlighting the elements we selected.

2. Debugger allows us to access the currently selected element through the $ variable in the console.

3. To view the associated scope, we can enter in the console: Angular.element ($). Scope ()

Vi. Scope Events Propagation (scope event spread)

The

Scope can propagate events in a way that is similar to DOM events. Events can be broadcast (http://code.angularjs.org/1.0.2/docs/api/ng. $rootScope scope# $broadcast) to child Scope or emit (http ://code.angularjs.org/1.0.2/docs/api/ng. $rootScope. scope# $emit) into parent Scope. (The current scope will also execute if there is a listener)

<! DOCTYPE html> 

Vii. Scope Life Cycle (Scope lifecycle)

In a browser-normal event stream, when the browser receives an event, it executes a corresponding JavaScript callback. Once the callback function has finished executing, the browser will redraw the DOM and return to the state of the wait event.

When the browser angular the JavaScript code in the execution environment, this means that angular is unaware of the change in model. To properly handle the changes to model, this command must enter the angular execution environment by making the $apply method accessible. Only the model changes in the $apply method will be correctly angular statistically. For example, a directive listens for DOM events, such as Ng-click, which must evaluate an expression in the $apply method.

After the expression is evaluated, a $digest is executed $apply method. In the $digest phase, scope examines all $watch listening expressions, comparing the current value to the old value. The dirty check (dirty checking) is asynchronous. This means that an assignment statement (such as $scope.username= "angular") will not immediately cause a $watch to be notified, instead, $watch notification will be deferred to the $digest phase. This delay is necessary because it combined multiple model updates into a single $watch notification, which guarantees that no other $watch is executing in the $WATCH notification process. If a $watch changes the value of model, it will force an additional $digest period.

1) Creation (create scope)

The root scope is created by $injector (Http://code.angularjs.org/1.0.2/docs/api/AUTO $injector) during application startup. In the process of template linking, some directive create a new child scope.

2) Watcher registration (registered watcher)

During template linking, Directive registers $watch in scope. These watch will be used as a value to propagate model to the DOM.

3 model mutation (model change)

In order for the changes to be detected correctly, we need to wrap them in scope. $apply. (The angular API has implicitly done this, so no additional $apply calls are required when doing synchronous work in controller or doing asynchronous work with $http or $timeout).

4) Mutation observation (change monitoring)

At the end of $apply, angular executes a $digest cycle in root scope, which is propagated to all child scopes. In the $digest cycle, all expressions or function registered $watch are checked to see if the model has changed, and if the change occurs, then the corresponding $watch listener will be invoked.

5) Scope destruction (Scope destruction)

When child scope is no longer necessary, the creator of child scope has the responsibility to destroy them (child scope) through the scope $destroy () API. This will stop $digest call propagation propagated into child scope, allowing the memory used by child scope model to be reclaimed by GC (garbage collector).

1. Scopes and Directives

During the compile phase, compiler relies on DOM templates to match directive. Directive can usually be divided into two main categories:

Observation type Directive (observing directives), such as dobule-curly expression {{expression}}, registers the listener with the $watch method. Whenever an expression (the value) changes, such directive must be notified to update view.
The Listener Type Directive (Listener directive), such as Ng-click, registers a listener into the DOM. When the listener for the DOM fires, Directive executes the associated expression and updates the view by using the $apply method.

When an external event (such as a user action, timer, or xhr) is monitored, the associated expression must be applied to scope through the $apply method, allowing all listeners to update correctly.

2. directives that Create scopes

In most cases, directive and scope are mutually influential, but no new scope instance is created. However, some directive (such as Ng-controller and Ng-repeat) create a new scope, with the additional child scope to the corresponding DOM element. We view the scope of any DOM element by using Angular.element (adomelement). Scope ().

3. Controllers and Scopes

In the following cases, scope and controller are mutually influential:

    1. Controller uses the scope exposure controller method to the stencil (view Ng-controller (Http://code.angularjs.org/1.0.2/docs/api/ng.directive:ngController)).
    2. Controller defines a method (behavior) that can change the model (properties on scope).
    3. Controller may register watch in model. These watch will be executed immediately after the controller action is performed.

4. Scope $watch Performance Considerations (Performance Considerations for scope $watch)

In angular, it is a common operation to detect the changes in the scope for the purpose of detecting the properties (Dirty checking). For this reason, this requires that the dirty checking function must be efficient. Be careful dirty the checking function does not do any DOM access, because DOM access is several orders of magnitude slower than accessing JavaScript object properties.

The above is about ANGULARJS Scope of data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.