Home Web Front-end JS Tutorial About $apply and optimized use in Angularjs

About $apply and optimized use in Angularjs

Jul 02, 2018 pm 01:59 PM
angular angularjs apply optimization

This article mainly introduces you to the relevant information about $apply and its optimized use in Angularjs. The article introduces it in great detail through sample code. Friends who need it can refer to it. Let’s take a look together.

Preface

For me, a complete novice in the front-end, I still know a little bit about Javascript. If I want to get started with angular JS directly, I encounter real resistance. Quite a few. However, I believe that as long as we work hard, even anti-human designs will not be a big problem.

Today, we are going to talk about the little star $apply in Angularjs. When our data is updated, but the view layer does not respond, we can always hear someone say, use apply. Then, being ignorant, we add $scope.$apply()## after the assignment code. # , and then I was surprised to find out. Oh, really updated.

However, sometimes, the compiler will ruthlessly return to you

Error: $digest already in progress


So, what are the causes of these phenomena? What exactly does $apply do? Listen to me coming slowly.

1. The role of $apply

The $apply() function can make expressions in the Angular context from outside the Angular framework Internal execution.


The above is a sentence from the AngularJs authoritative tutorial. What does that mean?


First of all, you must be aware that modifying the model in native js or third-party frameworks may not trigger view updates, such as setTimeout and jquery plug-ins. Why? Because they are out of the context of Angularjs, Angularjs cannot monitor data changes. See examples.

1.setTimeout

html:

<p>{{name}}</p>
Copy after login

js:

$scope.name="张三";
setTimeout(function(){
$scope.name = &#39;李四&#39;;
//$scope.$apply()
},500)
Copy after login

First of all, the name is equal to Zhang San. After 500ms, I assigned it to Li Si, but the page has not changed, it is still Zhang San.


However, if we release

$scope.$apply(), it will be normal. Zhang San successfully became Li Si.

2. Third-party plug-in

html:

<p>Date: <input type="text" id="datepicker"></p>
<p>
<header>所选日期</header>
{{selectedDate}}
</p>
Copy after login

js:

$scope.selectedDate = &#39;&#39;;
$( function() {
 $( "#datepicker" ).datepicker({
 onClose: function( selectedDate ) {
 $scope.selectedDate = selectedDate;
 // $scope.$apply();
 }
 });
} );
Copy after login

This is jquery's datepicker plug-in. When we select the date, the following date should appear, but now it does not. In this case, you must rely on $apply() to update the view.

In both of the above cases, data changes cannot be monitored because they are not in the Angularjs context. And what exactly did $apply do to cause the data to be updated normally?

In fact, $apply is equivalent to a trigger. Its function is to trigger the digest loop to update the view.

Digest is the core of Angularjs, which implements magical data binding. Any event that is triggered will definitely trigger the digest cycle. For example, our numerical ng events, click, and change, actually trigger the digest cycle.

So, what we did was actually trigger the digest cycle manually. Regarding the digest cycle, it is a digression. I will not introduce it in detail here. Students who want to know more about it can read books or Baidu.

2. Better use of digest loop

In Angularjs, in addition to $apply can trigger the digest loop, there are other methods , this loop can also be triggered. And $apply is often the worst choice. Some better options are recommended below.

1.$digest

$scope.$digest() is faster than $apply because it only updates the current scope The values ​​of domains and child scopes are ignored for the parent scope. And $apply also needs to evaluate the parent scope, which greatly consumes performance.

2.$timeout

Use $timeout to replace your setTimeout. $timeout is a built-in service of Angularjs, which is of course more suitable for the Angularjs environment. It will trigger the digest cycle implicitly, and it will delay execution and trigger the digest cycle the next moment after the previous digest cycle is completed, so that the

$digest already in progress
Copy after login
mentioned above will not occur.

We put the setTime code into $timeout

$timeout(function(){
$scope.name = &#39;李四&#39;;
},500)
Copy after login

This will work normally, look, there is nothing annoying Apply!

3.$evalAsync

The most recommended method should be this. If there happens to be a digest cycle currently executing, then it will put the operation that caused the digest cycle into the current digest cycle for execution. The $timeout is to wait until the current digest cycle is completed before executing the digest cycle again. So evalAsync executes faster and has better performance. We can call it like $timeout, that is,

$scope.$evalAsync(
   function( $scope ) {
   console.log( "$evalAsync" );
   }
  );
Copy after login

. The above is all I want to say today. There are still many secrets and better usage methods hidden in Angularjs. I hope you can study them in depth and share better articles.


The following is the executable code, you can explore it: https://codepen.io/hanwolfxue/pen/yEZbYQ

The above is the entire content of this article, I hope it will be helpful to everyone Learning will be helpful. For more related content, please pay attention to the PHP Chinese website!

related suggestion:

About the basic usage of built-in instructions in Angular4

How to clear the browser cache in angularJs

The above is the detailed content of About $apply and optimized use in Angularjs. For more information, please follow other related articles on the PHP Chinese website!

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)

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

How to optimize settings and improve performance after receiving a new Win11 computer? How to optimize settings and improve performance after receiving a new Win11 computer? Mar 03, 2024 pm 09:01 PM

How do we set up and optimize performance after receiving a new computer? Users can directly open Privacy and Security, and then click General (Advertising ID, Local Content, Application Launch, Setting Recommendations, Productivity Tools or directly open Local Group Policy Just use the editor to operate it. Let me introduce to you in detail how to optimize settings and improve performance after receiving a new Win11 computer. How to optimize settings and improve performance after receiving a new Win11 computer. One: 1. Press the [Win+i] key combination to open Settings, then click [Privacy and Security] on the left, and click [General (Advertising ID, Local Content, App Launch, Setting Suggestions, Productivity) under Windows Permissions on the right Tools)】.Method 2

In-depth interpretation: Why is Laravel as slow as a snail? In-depth interpretation: Why is Laravel as slow as a snail? Mar 07, 2024 am 09:54 AM

Laravel is a popular PHP development framework, but it is sometimes criticized for being as slow as a snail. What exactly causes Laravel's unsatisfactory speed? This article will provide an in-depth explanation of the reasons why Laravel is as slow as a snail from multiple aspects, and combine it with specific code examples to help readers gain a deeper understanding of this problem. 1. ORM query performance issues In Laravel, ORM (Object Relational Mapping) is a very powerful feature that allows

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Mar 06, 2024 pm 02:33 PM

Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Laravel, as a popular PHP framework, provides developers with rich functions and a convenient development experience. However, as the size of the project increases and the number of visits increases, we may face the challenge of performance bottlenecks. This article will delve into Laravel performance optimization techniques to help developers discover and solve potential performance problems. 1. Database query optimization using Eloquent delayed loading When using Eloquent to query the database, avoid

Discussion on Golang's gc optimization strategy Discussion on Golang's gc optimization strategy Mar 06, 2024 pm 02:39 PM

Golang's garbage collection (GC) has always been a hot topic among developers. As a fast programming language, Golang's built-in garbage collector can manage memory very well, but as the size of the program increases, some performance problems sometimes occur. This article will explore Golang’s GC optimization strategies and provide some specific code examples. Garbage collection in Golang Golang's garbage collector is based on concurrent mark-sweep (concurrentmark-s

C++ program optimization: time complexity reduction techniques C++ program optimization: time complexity reduction techniques Jun 01, 2024 am 11:19 AM

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

Laravel performance bottleneck revealed: optimization solution revealed! Laravel performance bottleneck revealed: optimization solution revealed! Mar 07, 2024 pm 01:30 PM

Laravel performance bottleneck revealed: optimization solution revealed! With the development of Internet technology, the performance optimization of websites and applications has become increasingly important. As a popular PHP framework, Laravel may face performance bottlenecks during the development process. This article will explore the performance problems that Laravel applications may encounter, and provide some optimization solutions and specific code examples so that developers can better solve these problems. 1. Database query optimization Database query is one of the common performance bottlenecks in Web applications. exist

See all articles