Bidirectional data binding of angular

Source: Internet
Author: User

---restore content starts---

When angular first entered the front-end developer Vision, one of the indelible impressions was its implementation of two-way data binding. This chapter first describes how to use this feature, and then explains in depth how its two-way binding mechanism is implemented.

Data-binding in angular refers to the automatic synchronization between the model models and view views. Angular implements two-way binding, which makes you feel that the data model is the only real source of data in the page. When the model changes, the view reflects the change, and vice versa. In layman's terms, the so-called two-way data binding, is nothing more than the interface from the operation can be reflected in real-time data, data changes can be displayed in real-time interface. According to each of the simplest examples:

<div ng-controller= "Counterctrl" >    <span ng-bind= "Counter" ></span>    <button ng-click= " counter++ ">increase</button></div>function  Counterctrl ($scope) {    = 1;}

The above example is very simple, each time a button is clicked, the data on the interface is added 1.

However, the novice is likely to encounter the following problems.

 var  app = Angular.module ("Test" , []); App.directive ( "Myclick", function   () { /span>return   (scope, element, attr) {Element.on ( "click", function   () {scope.counter  ++;    }); };}); App.controller ( "Counterctrl", function   ($scope) {$scope. Counter  = 0         <body ng-app= "Test" > <div ng-controller= "Counterctrl" > <button myclick>increase</button> <span ng-bind= "Counter" ></span> </div></body> 

The example above is also simple: to achieve: When you click the button, the span element counter plus 1. But in fact, this is not the view. However, the model counter indeed increased. In other words, there is no two-way binding of data that is implemented by angular. Test please visit: Http://plnkr.co/edit/?p=preview

However, if you are in scope.counter++, then add scope. $digest (); No problem, and the first example does not use the $digest function, if used instead of error. What's going on? Use native JavaScript below to see how things are done.

<! DOCTYPE html>     <meta CharSet="Utf-8" /> <title>Two-way binding</title>  <body OnLoad="Init()"> <button Ng-click="Inc">Increase 1</button> <button Ng-click="Inc2">Increase 2</button> <span Style="Color:Red" Ng-bind="Counter"></span> <span Style="Color:Blue" Ng-bind="Counter"></span> <span Style="Color:Green" Ng-bind="Counter"></span> <script Type="Text/javascript"> /* Data Model area Start */ VarCounter= 0; functionInc() {Counter++; } functionInc2() {Counter+=2; } /* Data Model area END */ /* Bind relation area start */ functionInit() {Bind(); } functionBind() { VarList=Document.Queryselectorall("[Ng-click]"); For (VarI=0;I<List.Length;I++) {List[I].OnClick= (function(Index) { Return function() {Window[List[Index].GetAttribute("Ng-click")]();Apply(); }; })(I); } } functionApply() { VarList=Document.Queryselectorall("[ng-bind= ' counter ']"); For (var I=0; I<list.; I++)  { List[i].= Counter;} } /* binding relationship Area end */ </script> </body> </HTML>            

Instead of using the DOM's OnClick method directly, it does a ng-click and then takes the ng-click corresponding function in bind and binds it to the OnClick event handler. Why would you do that? Since the data has changed, but has not yet been populated on the interface, we need to do some additional work here, namely adding the Apply () method. And since angular uses dirty detection, that is, it needs to do something on its own to trigger dirty detection, which is applied to the DOM element that corresponds to the data. So the previous piece of code just listens for the click, not ' Ng-click ', which does not trigger a dirty check and does not update to the view.

In some setter-based frameworks, it is possible to reset the values of the variables bound to the DOM elements when the data is set. However, the mechanism of dirty checking does not have this stage, it has no way to be notified immediately after the data change, so only apply () is called at each event entrance, and the changes of the data model are reflected on the view. In the real angular, it is generally the first dirty check of the model data, it really changed, only to set the value on the view.

Then, why in the Ng-click call $digest, will be error (is the first paragraph of code)? Because angular design, only allow one $digest to run at the same time, and Ng-click this built-in instruction has triggered the $digest, the current is not finished, so the error.

The above problem boils down to: how do I trigger a dirty check? When does it trigger? Then you have to mention the three important methods under scope: $digest, $apply, $watch. The next article describes these three functions in detail.

Finally, in the emphasis: angular to the DOM commonly used operations, XHR time to encapsulate, in the inside wrote the Trigger Digest () method of the flow. Dirty checks are only entered into $digest () after the instruction event is triggered, such as DOM events (such as entering text in input, clicking a button, and so on), XHR response Event ($http), browser location Change event ($location), Time event ($ Timeout, $interval).

Bidirectional data binding of angular

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.