About $apply and optimized use in Angularjs
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.
Error: $digest already in progressSo, 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?
1.setTimeout
html:<p>{{name}}</p>
$scope.name="张三"; setTimeout(function(){ $scope.name = '李四'; //$scope.$apply() },500)
$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>
$scope.selectedDate = ''; $( function() { $( "#datepicker" ).datepicker({ onClose: function( selectedDate ) { $scope.selectedDate = selectedDate; // $scope.$apply(); } }); } );
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
$timeout(function(){ $scope.name = '李四'; },500)
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" ); } );
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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 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

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

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! 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

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

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! 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
