search
HomeWeb Front-endJS TutorialAn in-depth analysis of the role and life cycle of $scope in the AngularJS framework_AngularJS

$scope is used throughout the entire Angular App. It is associated with the data model and is also the context for expression execution. With $scope, a channel is established between the view and the controller. Based on the scope view, When the data is modified, $scope will be updated immediately. When $scope changes, the view will be re-rendered immediately.

With $scope as a bridge, the business code of the application can be all in the controller, and the data is stored in the $scope of the controller.

201635151546605.jpg (463×316)

$scope is an object that connects the view (a DOM element) to the controller. In our MVC structure, this $scope will become the model, which provides an execution context bound to the DOM element (and its children).

Although it sounds a bit complicated, $scope is actually a JavaScript object that can be accessed by both the controller and the view, so we can use it to pass information between the two. In this $scope object, we store both data and functions that will be run on the view.

Every Angular application will have a $rootScope. This $rootScope is the top-level scope, which corresponds to the DOM element containing the ng-app directive attribute.

If $scope is not explicitly set on the page, Angular will bind data and functions here. The example in the first part relies on this to run successfully.

In this example, we will use $rootScope. In the main.js file, we add a name attribute to this scope. By executing this function in the app.run function, we ensure that it is executed before other parts of the application. You can think of the app.run function as the main method of your Angular application.


app.run(function($rootScope) {
 $rootScope.name = "Ari Lerner";
});

Now, we can access this name attribute anywhere in the view, using the template expression {{}}, like this:

{{ name }}

$rootScope
When the Angular application starts and generates a view, the root ng-app element will be bound to $rootScope. $rootScope is the top-level object of all $scopes and can be understood as a global scope object in the Angular application, so Attaching too much logic or variables to it is not a good idea, it is the same as polluting the Javascript global scope.


The role of $scope
The $scope object acts as a data model in Angular, which is the role of Model in the general MVC framework. But it is not exactly the same as a data model in the usual sense, because $scope does not process and operate data, it just Established a bridge between the view and HTML, allowing friendly communication between the view and the Controller.

Let’s further systematically divide its functions and functions:

  • Provides observers to monitor changes in the data model
  • Can notify the entire App of data model changes
  • Can be nested to isolate business functions and data
  • Provide context execution environment for expressions

Creating a new execution context in Javascript actually creates a new local context using a function. In Angular, when creating a new scope for a child DOM element, it actually creates a new scope for the child DOM element. execution context.

$scope life cycle
Angular also has the concept of 'event'. For example, when an input value bound to ng-model changes, or when an ng-click button is clicked, Angular's event loop will start. Event loop It is a very core concept in Angular. Since it is not the main focus of this article, I will not go into details. If you are interested, you can read the information yourself. The event here is processed in the Angular execution context, and $scope will evaluate the defined expression. At this point, the event loop is started, Angular will monitor all objects in the application, and the dirty value check loop will also be started.

The life cycle of $scope has 4 stages:

1. Create

When a controller or directive is created, Angular will use $injector to create a new scope, and then pass the scope into it when the controller or directive is run.

2. Link

After Angular is started, all $scope objects will be attached or linked to the view, and all functions that create $scope objects will also be attached to the view. These scopes will be registered to run when the Angular context changes. Function. That is, the $watch function. Angular uses these functions or when to start the event loop.

3. Update

Once the event loop starts running, it will start to perform its own dirty value detection. Once a change is detected, the callback function specified on $scope will be triggered

4. Destroy

Generally speaking, if a $scope is no longer needed in the view, Angular will clean it up by itself. Of course, it can also be cleaned manually through the $destroy() function.

ng-controller

To explicitly create a $scope object, we need to attach a controller object to the DOM element, using the ng-controller directive attribute:


<div ng-controller="MyController">
 {{ person.name }}
</div>

ng-controller指令给所在的DOM元素创建了一个新的$scope 对象,并将这个$scope 对象包含进外层DOM元素的$scope 对象里。在上面的例子里,这个外层DOM元素的$scope 对象,就是$rootScope 对象。这个scope链是这样的:

201635151716443.png (253×188)

现在,MyController 给我们建立了一个可以从DOM元素内部直接访问的$scope 对象。下面我们在的这个$scope 里创建一个person对象,在main.js中:

app.controller('MyController', function($scope) {
 $scope.person = {
  name: "Ari Lerner"
 };
});


现在我们可以在有ng-controller='MyController'属性的DOM元素的任何子元素里访问这个person 对象,因为它在$scope上。
除了一个例外,所有scope都遵循原型继承(prototypal inheritance),这意味着它们都能访问父scope们。对任何属性和方法,如果AngularJS在当前scope上找不到,就会到父scope上去找,如果在父scope上也没找到,就会继续向上回溯,一直到$rootScope 上。

唯一的例外:有些指令属性可以选择性地创建一个独立的scope,让这个scope不继承它的父scope们。

举个例子,假设我们有一个ParentController ,含有一个person 对象,又有一个ChildController 想要访问这个对象:

app.controller('ParentController', function($scope) {
 $scope.person = {greeted: false};
});
 
app.controller('ChildController', function($scope) {
 $scope.sayHello = function() {
  $scope.person.greeted = true;
 }
});

当我们在view里把ChildController 绑定到ParentController 之下,在子元素里我们就能访问ParentController 创建的父scope的属性,像访问ChildController 自己的scope中的属性一样:

<div ng-controller="ParentController">
 <div ng-controller="ChildController">
  <input type="text" ng-model="person.name" placeholder="Name"></input>
  <a ng-click="sayHello()">Say hello</a>
 </div>
 {{ person }}
</div>


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor