Summary of $apply method and $watch method in Angularjs _angularjs

Source: Internet
Author: User


The $apply method and $watch method used in Angularjs are summarized in this paper. Share to everyone for your reference, specific as follows:



Introduction



Recently in the project to encapsulate the control of the use of the $watch method to monitor the changes in the value of the module, when the small series on this method is not very understanding, so on the Internet to find some information to learn, the following small series to give you a brief introduction to some angularjs in the scope of the provision $apply Methods to propagate model changes and $watch methods to monitor module changes.



$apply Use Stories



Angularjs external Controllers (DOM events, external callback functions such as jQuery UI space, etc.) call the ANGULARJS function, you must call $apply. In this case, you need to command Angularjs to refresh yourself (model, view, etc.), $apply is used to do this thing. When we use $apply this method, as long as we can, please pass to execute the code and function to $apply to execute, instead of executing those functions and then call $apply.



Let's look at a demo and write a timer to change the value of name after two seconds:


<! DOCTYPE html>
<html>
<head>
   <meta http-equiv = "Content-Type" content = "text / html; charset = UTF-8">
   <title> RunJS </ title>
   <script src = "http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"> </ script>
   <script src = "http://cdn.bootcss.com/angular.js/1.2.9/angular-route.min.js"> </ script>
   <script src = "serviceJS01.js"> </ script>
</ head>
<body ng-app = "myApp">
<div ng-controller = "firstController" ng-click = "show ()">
{{name}}
   {{age}}
</ div>
</ body>
</ html>
<script>
   var app = angular.module ("myApp", []);
   app.controller ('firstController', function ($ scope, $ timeout) {
     setTimeout (function () {
       $ scope. $ apply (function () {
         $ scope.name = "李四";
       })
     }, 2000);
     $ scope.name = "张三";
     $ scope.age = '10 ';
     $ scope.show = function () {
       $ scope.name = 'name after clicking';
     }
   $ timeout (function () {
     $ scope.age = '50 ';
   }, 2000);
   })
</ script>


In the code above, if we don't use $apply to propagate the change of the name value, we simply write the $scope.name= "Dick" code in the SetTimeout function, and the value displayed on the interface does not change at all.



$watch method for monitoring module changes



$watch function can give you a notification when a part of your data model is changed. You can monitor the properties of a single object, or you can monitor the results that need to be computed (functions), which can be monitored by $watch functions as long as they can be accessed as attributes, or as a JavaScript function. Its function is signed by:


$watch (WATCHFN, watchaction, Deepwatch)


WATCHFN parameter : This is our listener local target object, it is a string with angular expression or function;



watchaction parameter : This is a function or expression that will be invoked when the WATCHFN is changed. If it is the form of a function, it will receive the new and old two values of the WATCHFN, as well as the reference to the scope object. Its functions are signed as function (NewValue, oldValue, scope).



deepwatch parameter : If set to True, this optional boolean parameter will command angular to check whether each property of the monitored object has changed. You can use this parameter if you want to monitor the elements in the array, or all the attributes on the object, rather than just monitoring a simple value.



Below look at a demo, when the cost of more than 100, the freight is 0 otherwise freight is 10:


<! DOCTYPE html>
<html>
<head>
  <meta http-equiv = "Content-Type" content = "text / html; charset = UTF-8">
  <title> RunJS </ title>
  <script src = "http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"> </ script>
  <script src = "http://cdn.bootcss.com/angular.js/1.2.9/angular-route.min.js"> </ script>
  <script src = "serviceJS01.js"> </ script>
</ head>
<body ng-app = "myApp">
<div ng-controller = "firstController" ng-click = "show ()">
  <p> Price: <input type = "text" ng-model = "iphone.money"> </ p>
  <p> Number: <input type = "text" ng-model = "iphone.num"> </ p>
  <p> Cost: <span> {{sum () | currency: '¥'}} </ span> </ p>
  <p> Shipping: <span> {{iphone.fre | currency: '¥'}} </ span> </ p>
  <p> Total: <span> {{sum () + iphone.fre | currency: '¥'}} </ span> </ p>
</ div>
</ body>
</ html>
<script>
  var app = angular.module ("myApp", []);
  app.controller ('firstController', function ($ scope) {
  $ scope.iphone = {
    money: 5,
    num: 1,
    fre: 10
  };
    $ scope.sum = function () {
      return $ scope.iphone.money * $ scope.iphone.num;
    }
    $ scope. $ watch ($ scope.sum, function (newValue, oldValue) {
      $ scope.iphone.fre = newValue> = 100? 0: 10
    })
  })
</ script> 


$watch This function is often used in projects, so we need to have a flexible grasp of the function so that we can be more convenient when customizing the controls or accomplishing some of the more complex requirements.



Summary



The above is a summary of the two methods, these are relatively introductory knowledge, if you want to better understand this knowledge also need us to study well in the project.



Source Address: Http://runjs.cn/code/ovjwuxhn



More readers interested in ANGULARJS related content can view the site topics: "Angularjs Introduction and Advanced Tutorials" and "ANGULARJS MVC Framework Summary"



I hope this article will help you to Angularjs program design.


Related Article

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.