Home  >  Article  >  Web Front-end  >  About $apply and optimized use in Angularjs

About $apply and optimized use in Angularjs

不言
不言Original
2018-07-02 13:59:101575browse

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