Home Web Front-end JS Tutorial A brief discussion on the method of implementing two-way binding in angular.js $watch $digest $apply_AngularJS

A brief discussion on the method of implementing two-way binding in angular.js $watch $digest $apply_AngularJS

May 16, 2016 pm 03:36 PM
angular apply watch

Features in Angular.js, two-way binding.

What a magical function that allows changes in the view to be directly reflected in the data. Changes in the data are notified to the view in real time. How to do it?

This is thanks to the following 3 important methods of scope:

$watch
$digest
$apply

What are their differences? Let’s introduce them:

$watch
This is a listener that listens to data on the scope

Method description:

$scope.$watch('参数',function(newValue,oldValue){
 //逻辑处理
})
Copy after login

We created a listener above.
‘Parameter’ is an object (or an attribute of an object) under the $scope object. Note that this is in string form.

Suppose you want to monitor the $scope.name property.

$scope.$watch('name',function(newValue,oldValue){
 //逻辑处理
})
Copy after login

As in the above code, ‘name’ needs quotes

The parameter is followed by a callback function. The callback function parameter returns the monitored attribute, the new value after the change, and the old value before the previous change.

$digest

He is responsible for checking whether the data in the scope has changed. If a certain attribute changes, it will immediately notify the listener of this attribute (the listener registered by $watch), trigger the listener, and execute the callback function.

$apply

This method is very similar to $digest, $digest checks all data in the scope
$apply is equivalent to checking all data in rootScope, it will check all data from parent to child

$apply() == $rootScope.$digest()

The $apply() method has two forms.

The first one accepts a function as a parameter.
This triggers the $digest function and executes the function

in the parameter once

The second type does not accept any parameters.
This just triggers a $digest parent-to-child cycle

In Angular.js, $digest will not be called directly, but $scope.$apply() is used instead

I didn’t set the monitor, why can the view and data be bound in two directions

For example, a text box ng-model="name"
At this time, there is actually an attribute name under the $scope object to correspond to the two-way binding with the above view

How to achieve it?

In fact, when we define ng-model="name" or ng-bind="name" or {{name}}
At this time, angular.js will automatically set a listener for the "name" attribute on the $scope model:

$scope.$watch('name', function(newValue, oldValue) {
  //监听 name 属性的变化
});
Copy after login

It turns out that angular.js helps us automatically create a listener, so this property and $scope.name data will be two-way bound in real time.

Of course, sometimes you will find that the data has changed. But the UI is not refreshed. Is the two-way binding invalid?

No

It’s just that when the $scope model traverses the digest loop, your data has not been returned yet,

For example, when calling a method asynchronously, the data returned by callbac
For example, you set a scheduled trigger function in setTimeout, and then modify the model data
In short, the digest cycle of the $scope model was missed, resulting in the model not notifying the UI to refresh according to new data.

What should I do if I encounter such a problem?

We have to manually call digest to check the data in a loop to achieve two-way binding

As we have said above, usually do not call the digest method directly, but manually call the $apply method to indirectly trigger the $digest loop.

As follows:

setTimeout(function() {
 $scope.name= '一介布衣';
 $scope.$apply();
}, 2000);
Copy after login

The problem is here, it’s time to manually call the apply method

So far, angular.js has automatically implemented the $apply() method for some directives and services.

For example, ng-click, ng-model, $timeout service, $http service, etc.

After calling, angular.js will automatically call $apply() for us to achieve two-way data binding.

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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
1665
14
PHP Tutorial
1270
29
C# Tutorial
1250
24
Users encounter rare glitches: Samsung Watch smartwatches suddenly experience white screen issues Users encounter rare glitches: Samsung Watch smartwatches suddenly experience white screen issues Apr 03, 2024 am 08:13 AM

You may have encountered the problem of green lines appearing on the screen of your smartphone. Even if you have never seen it, you must have seen related pictures on the Internet. So, have you ever encountered a situation where the smart watch screen turns white? On April 2, CNMO learned from foreign media that a Reddit user shared a picture on the social platform, showing the screen of the Samsung Watch series smart watches turning white. The user wrote: "I was charging when I left, and when I came back, it was like this. I tried to restart, but the screen was still like this during the restart process." Samsung Watch smart watch screen turned white. The Reddit user did not specify the smart watch. Specific model. However, judging from the picture, it should be Samsung Watch5. Previously, another Reddit user also reported

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

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!

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!

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

How vue3 data monitors watch/watchEffect How vue3 data monitors watch/watchEffect May 12, 2023 pm 06:31 PM

We all know that the function of the listener is to trigger every time the reactive state changes. In the combined API, we can use the watch() function and watchEffect() function. When you change the reactive state, it may be triggered at the same time. Trigger Vue component updates and listener callbacks. By default, user-created listener callbacks will be called before the Vue component is updated. This means that the DOM you access in the listener callback will be the state it was in before it was updated by Vue. So, let’s take a look, how can we make good use of them? What's the difference between them? The watch() function watch needs to listen to a specific data source, such as listening to a ref. The first parameter of watch can be

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

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

See all articles