Home Web Front-end JS Tutorial How to use two-way binding in AngularJs

How to use two-way binding in AngularJs

Jun 22, 2018 pm 01:45 PM
angularjs Two-way binding data binding

This article mainly introduces the two-way binding principle (data binding mechanism) of AngularJs. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look.

So what is two-way binding? Let’s briefly explain it below.

First we need to understand data binding. The website pages we see are composed of two parts: data and design. Converting the design into a language that the browser can understand is what HTML and CSS mainly do. Displaying data on the page and having certain interactive effects (such as clicks and other user operations and corresponding page reactions) is the main job of js. Many times we cannot refresh the page (get request) every time we update data. Instead, we request relevant data from the backend and update the page (post request) by loading without refreshing. Then after the data is updated, the corresponding location on the page can automatically make corresponding modifications, which is data binding.

In the previous development model, this step usually uses jq to operate the DOM structure to update the page. But this brings a lot of code and a lot of operations. If we can determine the operations that need to be performed on the page from the data obtained from the backend at the beginning, when the data changes, the relevant content of the page will also automatically change, which will greatly facilitate the development of front-end engineers. In the new framework (angualr, react, vue, etc.), by monitoring the data, if changes are found, the page will be modified according to the rules that have been written, thus realizing data binding. It can be seen that data binding is a modification of M (model, data) to V (view) through VM (model-view, the transformation rule between data and pages).

The two-way binding adds a reverse path. When the user operates the page (such as entering a value in Input), the data can change in time, and according to the change in the data, corresponding modifications are made in another part of the page. A common example is the shopping cart in Taobao. When the quantity of goods changes, the price of the goods can also change in time. This achieves a two-way binding of V-M-VM-V.

AngularJs sets a listening queue on the scope model to listen for data changes and update the view. Every time you bind something to view (html), AngularJs will insert a $watch into the $watch queue to detect whether there are changes in the model it monitors. The $digest loop fires when the browser receives an event that can be handled by the angular context. $digest will iterate through all $watches. Thus updating the DOM.

$watch

This is somewhat similar to our observer pattern. Under the current scope $scope, we create a monitor $watchers and a listener$ watch, $watchers are responsible for managing all $watches. Every time we bind it to the UI, we will automatically create a $watch and put it in $watchers.

controller.js

app.controller('MainCtrl', function($scope) {
 $scope.Hello = "Hello";
 $scope.world = "World";
});
Copy after login

index.html

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

Here, even if we add two variables to $scope, but there is only one It is bound to the UI, so only one $watch

$digest

can be processed by the angular context when the browser receives it. event, the $digest loop will trigger. $digest will traverse our $watches. If $watch has no changes, the loop detection will stop. If at least one has been updated, the loop will be triggered again until all $watches have no changes. This ensures that each model will not change again. This is the Dirty Checking mechanism

controller.js

app.controller(&#39;MainCtrl&#39;, function() {
 $scope.name = "Foo";

 $scope.changeFoo = function() {
  $scope.name = "Bar";
 }
});
Copy after login

index.js

<p>{{ name }}</p>
<button ng-click="changeFoo()">Change the name</button>
Copy after login
  1. When we press the button

  2. The browser receives an event and enters the angular context.

  3. The $digest loop begins to execute, querying whether each $watch changes.

  4. Because the $watch monitoring $scope.name reports a change, it will force another $digest cycle.

  5. New $digest loop no changes detected.

  6. Update the DOM corresponding to the new value of $scope.name.

$apply

$apply We can directly understand it as refreshing the UI. If you call $apply when the event is triggered, it will enter the angular context. If it is not called, it will not enter, and the subsequent $digest detection mechanism will not trigger

app.directive(&#39;clickable&#39;, function() {
 return {
  restrict: "E",
  scope: {
  foo: &#39;=&#39;
  },
  template: &#39;<ul style="background-color: lightblue"><li>{{foo}}</li></ul>&#39;,
  link: function(scope, element, attrs) {
  element.bind(&#39;click&#39;, function() {
   scope.foo++;
   console.log(scope.foo);
  });
  }
 }
});
Copy after login

When we call the clickable instruction, we can see that the value of foo has increased, but the content displayed on the interface has not changed. The $digest dirty detection mechanism is not triggered, and the $watch to detect foo is not executed.

Two forms of $apply() method

1) No parameters

$scope.$apply();
Copy after login
element.bind(&#39;click&#39;, function() {
 scope.foo++;
 //if error
 scope.$apply();
});
Copy after login

When we use this form, if the program occurs before scope.$apply Exception, then scope.$apply is not executed and the interface will not be updated

2) If there are parameters

$scope.$apply(function(){
 ...
})
Copy after login
element.bind(&#39;click&#39;, function() {
 scope.$apply(function() {
  scope.foo++;
 });
})
Copy after login

If you use this form, even if an exception occurs later, the data will still be updated.

Using $watch in AngularJS

Common usage:

$scope.name = &#39;Hello&#39;;
$scope.$watch(&#39;name&#39;, function(newValue, oldValue) {
 if (newValue === oldValue) { return; } 
 $scope.updated++;
});
Copy after login

传入到$watch()中的第二个参数是一个回调函数,该函数在name的值发生变化的时候会被调用。

如果要监听的是一个对象,那还需要第三个参数:

$scope.data.name = &#39;Hello&#39;;
$scope.$watch(&#39;data&#39;, function(newValue, oldValue) {
 if (newValue === oldValue) { return; } 
 $scope.updated++;
}, true);
Copy after login

表示比较的是对象的值而不是引用,如果不加第三个参数true,在 data.name 变化时,不会触发相应操作,因为引用的是同一引用。

总结

1) 只有在$scope变量绑定到页面上,才会创建 $watch

2) $apply决定事件是否可以进入angular context

3) $digest 循环检查model时最少两次,最多10次(多于10次抛出异常,防止无限检查)

4) AngularJs自带的指令已经实现了$apply,所以不需要我们额外的编写

5) 在自定义指令时,建议使用带function参数的$apply

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在javaScript中如何使用手机号码校验工具类PhoneUtils

在微信小程序中如何实现下载进度条

在微信小程序中如何使用video组件播放视频

在微信小程序中如何使用audio组件

在微信小程序中有关功能函数总结(详细教程)

The above is the detailed content of How to use two-way binding 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 implement data binding function in SwiftUI using MySQL How to implement data binding function in SwiftUI using MySQL Jul 30, 2023 pm 12:13 PM

How to use MySQL to implement data binding function in SwiftUI. In SwiftUI development, data binding can realize automatic updating of interface and data, improving user experience. As a popular relational database management system, MySQL can store and manage large amounts of data. This article will introduce how to use MySQL to implement data binding function in SwiftUI. We will make use of Swift's third-party library MySQLConnector, which provides connections and queries to MySQL data.

Detailed explanation of data binding functions in Vue documentation Detailed explanation of data binding functions in Vue documentation Jun 20, 2023 pm 10:15 PM

Vue is an open source JavaScript framework mainly used for building user interfaces. The core of Vue is data binding, which provides a convenient and efficient way to achieve two-way binding between data and views. Vue's data binding mechanism is handled through some special functions. These functions can help us automatically bind the data in the template to the corresponding properties in the JavaScript object, so that when the properties in the JavaScript object are modified, the data in the template will also automatically

How to use the v-once directive to implement one-time rendering of data binding in Vue How to use the v-once directive to implement one-time rendering of data binding in Vue Jun 11, 2023 pm 01:56 PM

Vue is a popular front-end JavaScript framework that provides many instructions to simplify the data binding process. One of the very useful instructions is v-once. In this article, we will delve into the use of the v-once directive and how to implement data-bound one-time rendering in Vue. What is the v-once instruction? v-once is a directive in Vue. Its function is to cache the rendering results of elements or components so that their rendering process can be skipped in subsequent updates.

Using v-model's two-way binding in Vue to optimize application data performance Using v-model's two-way binding in Vue to optimize application data performance Jul 17, 2023 pm 07:57 PM

Using v-model's two-way binding in Vue to optimize application data performance In Vue, we often use the v-model directive to achieve two-way binding between form elements and data. This two-way binding greatly simplifies the development process and improves user experience. However, since v-model needs to listen to the input event of the form element, this two-way binding may cause certain performance problems when the amount of data is large. This article will introduce how to optimize data performance when using v-model and provide a

Vue error: v-model cannot be used correctly for two-way data binding. How to solve it? Vue error: v-model cannot be used correctly for two-way data binding. How to solve it? Aug 19, 2023 pm 08:46 PM

Vue error: v-model cannot be used correctly for two-way data binding. How to solve it? Introduction: Two-way data binding is a very common and powerful feature when developing with Vue. However, sometimes we may encounter a problem, that is, when we try to use v-model for two-way data binding, we encounter an error. This article describes the cause and solution of this problem, and provides a code example to demonstrate how to solve the problem. Problem Description: When we try to use v-model in Vue

The latest 5 angularjs tutorials in 2022, from entry to mastery The latest 5 angularjs tutorials in 2022, from entry to mastery Jun 15, 2017 pm 05:50 PM

Javascript is a very unique language. It is unique in terms of the organization of the code, the programming paradigm of the code, and the object-oriented theory. The issue of whether Javascript is an object-oriented language that has been debated for a long time has obviously been There is an answer. However, even though Javascript has been dominant for twenty years, if you want to understand popular frameworks such as jQuery, Angularjs, and even React, just watch the "Black Horse Cloud Classroom JavaScript Advanced Framework Design Video Tutorial".

Solve Vue error: Unable to use v-model for two-way data binding Solve Vue error: Unable to use v-model for two-way data binding Aug 25, 2023 pm 04:49 PM

Solve Vue error: Unable to use v-model for two-way data binding. When developing with Vue, the v-model instruction is often used to achieve two-way data binding, but sometimes we encounter a problem when using v- An error will be reported when using the model, and two-way data binding cannot be performed correctly. This may be due to some common errors. Below I will introduce several common situations and corresponding solutions. The props attribute of the component is not set correctly. When we use the component, if we need to pass v-

Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Jun 27, 2023 pm 07:37 PM

In today's information age, websites have become an important tool for people to obtain information and communicate. A responsive website can adapt to various devices and provide users with a high-quality experience, which has become a hot spot in modern website development. This article will introduce how to use PHP and AngularJS to build a responsive website to provide a high-quality user experience. Introduction to PHP PHP is an open source server-side programming language ideal for web development. PHP has many advantages, such as easy to learn, cross-platform, rich tool library, development efficiency

See all articles