Home php教程 PHP开发 Detailed explanation of important instructions in angular ($eval, $parse and $compile)

Detailed explanation of important instructions in angular ($eval, $parse and $compile)

Dec 09, 2016 pm 01:59 PM
angular

Among Angular's services, there are some services that you have to understand, because they can be said to be the core of ng. Today, I want to introduce the two core services of ng, $parse and $compile. In fact, a lot of people talk about these two services, but there are 100 Hamlets for every 100 readers. I am here to talk about my understanding of these two services.

You may have questions, $eval is not actually a service. It is a method in the scope and cannot be regarded as a service. Moreover, it is also based on parse, so it can only be regarded as another way of writing $parse. , let’s take a look at the definition of $eval in the ng source code and we’ll know

$eval: function(expr, locals) {
    return $parse(expr)(this, locals);
   },
Copy after login

I believe everyone will understand after reading the source code. Okay, now let’s start the explanation of the two core services. If you feel If what I said is wrong, please feel free to point it out in the comment area or private chat, so as not to harm other readers.

When I talk about these two services, I will first talk about a concept in this post: context

I believe that many people have heard of this "context", but it may be a bit vague. Let me explain it to you here. Let’s see if everyone accepts this statement.

Do you still remember angular’s ​​data binding? For example: I now have a controller called TestCtrl, and its content is as follows:

.controller('TestCtrl', function($scope) {
      $scope.test = "Boo!!!"
  })
Copy after login

And in html our code is like this

<body ng-controller="TestCtrl">
  {{test}}
</body>
Copy after login

Well, everyone knows it without thinking As a result, the words Boo!!! will definitely be displayed on the page.

But what if I delete the ng-controller directive? That is to say, I did not declare the controller in html. What will happen if you bind {{test}} directly?

There is only one result, that is, there is nothing on the page (ps: because you declared ng-app). Do you understand this?

The controller is equivalent to a context container. The real context is actually $scope. When the page is bound to test, if a controller is declared, the current context is the $scope in the controller. ng will look for your control. Does the context $scope of the controller have a test? If so, it will of course be displayed, but what about when you don’t declare the controller? His context container is ng-app, then his real context is $rootScope. At this time, he will look for $rootScope to see if there is a test.

Okay, we have finished talking about the concept of context. It is actually quite easy to understand. It is basically very similar to this

So let’s get down to business, let’s start talking about $parse. The first thing we need to look at is ng’s API documentation

var getter = $parse(&#39;user.name&#39;);
var setter = getter.assign;
var context = {user:{name:&#39;angular&#39;}};
var locals = {user:{name:&#39;local&#39;}};
 
expect(getter(context)).toEqual(&#39;angular&#39;);
setter(context, &#39;newValue&#39;);
expect(context.user.name).toEqual(&#39;newValue&#39;);
expect(getter(context, locals)).toEqual(&#39;local&#39;);
Copy after login

What you see are the most cost-effective lines of code for the $parse service in the ng document.

getter and setter are the well-known get method and set method. context and locals are just json objects, the purpose is to simulate Contextual relationship

The following four statements that you see can eventually pass the test. Now let’s analyze them one by one. Before the analysis, I have to explain what $parse is.

The $parse service is actually a function of parsing expressions. Just like ng-model="test", when you write this in HTML, who knows that in ng-model="test", in fact, what you want to bind is in the scope (context) of the current controller (context container) For the value in test, ng uses the $parse service to help you parse the expression, so when calling the $parse service, you need to pass the context object to let ng know where you want to go to find you. This test.

So we see the first line of test code is like this:

getter(context)).toEqual(&#39;angular&#39;) //实际上就是 $parse(&#39;user.name&#39;)(context)
Copy after login

In this context, it is the context. The principle of returning the "angular" string is through these three steps:

1. Get the current expression user.name

2. Get the current context object {user:{name:'angular'}}

3. Find the expression in the upper and lower object, and finally get the character "angular" created

So this test code is successful.

Let’s look at the second method, the setter method

setter(context, &#39;newValue&#39;);//实际上就是 $parse(&#39;user.name&#39;).assign(context, &#39;newValue&#39;)
expect(context.user.name).toEqual(&#39;newValue&#39;);//测试数据上下文的值是否被改变
Copy after login

The setter method here is actually a change value method

1. Get the current expression user.name

2. Get the current context object {user: {name:'angular'}}

3. Change the value in the expression and program the context object {user:{name:'newValue'}}

Then the context object changes and reuse the getter method to get the expression expression, the context has been changed from {user:{name:'angular'}} --> {user:{name:'newValue'}}, and the value of the expression finally obtained is naturally "newValue", so the test The code also passed.

expect(getter(context, locals)).toEqual(&#39;local&#39;);//实际上就是$parse(&#39;user.name&#39;)(context, locals)
Copy after login

What we want to show here is actually the context replacement function.

In the getter method, we can not only select the first context, but if we pass the second parameter, the first context will be overwritten by the second context. Note that it is overwritten.

1. Get the current context The expression of user.name

2. Get the current context object {user:{name:'angular'}}

3. Overwrite the current context {user:{name:'local'}}

4. Get The value of the expression after parsing

Back to $eval, we can see from the $eval source code that $eval only has a get function and no set function, but sometimes we can choose to pass a second context to achieve the effect of modifying the value.

The $parse service has been finished here, and the next step is $compile

--------------------------------- --------------------

If you understand the concept of $parse, I think $compile is almost understood. In fact, it is very similar to $parse. But it parses a piece of html code, and its function is to turn a dead template into a live template, which is also the core service of the command.

For example, if you have a piece of html code

{{test}}

, if you put this code directly in the html code, what content will it display? I won’t say that everyone should also Understand. This is a dead template, and the so-called live template means that all the data in it has been bound by data. {{test}} will automatically find the current context to bind the data. The last thing displayed is the live template, that is, the template that has been data bound.

$compile('dead template') (context object), in this way, the dead template is programmed into a live template, and you can perform operations on this live html code, such as adding it to the current node, etc.

But in the instruction, she will return two functions pre-link and post-link

The first one executed is pre-link. Its traversal order for the same instruction is from the parent node to the child node. At this stage, the DOM node has not yet stabilized and cannot perform some binding event operations, but we can perform some initialization data processing here.

The second execution is post-link, which is what we often call the link function. It traverses from child nodes to parent nodes. At this stage, the DOM node has stabilized, and we usually do a lot of work here. operation.


Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Let's talk about metadata and decorators in Angular Let's talk about metadata and decorators in Angular Feb 28, 2022 am 11:10 AM

This article continues the learning of Angular, takes you to understand the metadata and decorators in Angular, and briefly understands their usage. I hope it will be helpful to everyone!

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

Angular + NG-ZORRO quickly develop a backend system Angular + NG-ZORRO quickly develop a backend system Apr 21, 2022 am 10:45 AM

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

See all articles