天天看點

【AngularJS】4.AngularJS $scope裡面的$apply方法和$watch方法

1. Angularjs $scope 裡面的$apply 方法

(1)$apply 方法作用: Scope 提供$apply 方法傳播 Model 的變化 。

(2)$apply 方法使用情景: AngularJS 外部的控制器(DOM 事件、外部的回調函數如 jQuery UI 空間等)調用了 AngularJS 函數之 後,必須調用$apply。在這種情況下,你需要指令 AngularJS 重新整理自已(模型、視圖等),$apply 就是 用來做這件事情的。

(3)$apply 方法注意事項: 隻要可以,請把要執行的代碼和函數傳遞給$apply 去執行,而不要自已執行那些函數然後再調用$apply。 

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>無标題文檔</title>
        <script type="text/javascript" src="angular.min.js"></script>
    </head>
    <body>
      <div ng-app="myApp">

          <div ng-controller="firstController" ng-click="show();">
            {{name}} {{age}}
          </div>

      </div>
      <script type="text/javascript">
          var app = angular.module("myApp", []);
          app.controller('firstController',function($scope,$timeout){

             setTimeout(function(){

                 $scope.$apply(function(){

                     $scope.name='1111';

                 });

             },2000);


              $timeout(function(){
                  $scope.age='50';

              },2000);



              $scope.name='張三';
              $scope.age='10';

              $scope.show=function(){
                  alert('111');
                  $scope.name='點選後的name';
              }

          });
      </script>
       
    </body>
</html>
           

2. Angularjs $scope 裡面的$watch 方法

(1)$watch 方法作用:  $watch 方法監視 Model 的變化。 

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>無标題文檔</title>
        <script type="text/javascript" src="angular.min.js"></script>
    </head>
    <body>
      <div ng-app="myApp">

          <div ng-controller="firstController">

              <p>單價:<input type="text" ng-model="iphone.money"></p>
              <p>個數:<input type="text" ng-model="iphone.num"></p>
              <p>費用:<span>{{ sum() | currency:'¥' }}</span></p>
              <p>運費:<span>{{iphone.fre | currency:'¥'}}</span></p>
              <p>總額:<span>{{ sum() + iphone.fre | currency:'¥'}}</span></p>
          </div>

      </div>
      <script type="text/javascript">
          var app = angular.module("myApp", []);
          app.controller('firstController',function($scope){
                // $scope.name='fasdfds';
                  $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){

                 console.log(newValue);
                 console.log(oldValue);
                  $scope.iphone.fre=newValue>=100 ? 0:10;


              });


          });
      </script>
       
    </body>
</html>