search
HomeWeb Front-endJS TutorialAbout $apply and optimized use in Angularjs

About $apply and optimized use in Angularjs

Jul 02, 2018 pm 01:59 PM
angularangularjsapplyoptimization

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>

js:

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

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>

js:

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

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
mentioned above will not occur.

We put the setTime code into $timeout

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

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" );
   }
  );

. 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
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
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

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 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.