2013-08-01 96 views
2

這是我的代碼:

<!doctype html> 
<html lang="en-US" ng-app> 
    <!--Head--> 
    <head> 
     <meta charset="UTF-8"> 
     <title>Lesson 5 - ng-show & ng-hide</title> 
     <meta name="viewport" content="width=device-width"> 
     <style type="text/css"> 
      * { 
       box-sizing: border-box; 
      } 
      body { 
       font: 16px/1.5 Consolas; 
       color: #222; 
       margin: 5em; 
      } 
     </style> 
    </head> 
    <!--Body--> 
    <body> 

     <div ng-controller="information"> 
      <!--Input--> 
      <label for="name"> 
       Name: 
       <input type="text" name="username" id="username" placeholder="Your name here please" ng-model="name"/> 
      </label> 
      <br> 
      <label> 
       Hide? 
       <input type="checkbox" ng-model="checked"/> 
      </label> 
      <!--Div that is hidden--> 
      <div ng-hide="checked"> 
       Hidden Message here 
       <br> 
       Welcome {{ name || "user" }}! 
      </div> 

     </div> 
     <script type="text/javascript" src="angular_1.0.7.js"></script> 
     <script type="text/javascript"> 
      var information = function ($scope) { 
       $scope.$watch(function() { 
        console.log($scope.name); 
       }); 
      }; 
     </script> 
    </body> 
</html> 

如果你來看,這並更改<input>標籤內的值,然後你會看到,在控制檯窗口中,您更改值每一次,值你把它改成,是輸出的兩倍,如下圖所示:

enter image description here

爲什麼會出現這種情況?

回答

7

手錶被多次調用每digest cycle

的$消化循環不斷迭代直到模型穩定,這意味着$ evalAsync隊列爲空,$觀察名單沒有檢測到任何變化。

當您鍵入一個字符時,Angular會進入摘要循環(因爲Angular會自動添加一個事件偵聽器,因爲您正在使用ng-model)並檢測到一個更改。然後再次通過循環確保沒有其他更改。它是這樣做的,因爲如果$ watch觸發,它可能會改變其他一些監視的屬性,然後需要檢測,因此它的監視功能可以被執行。

+0

謝謝,這是我想知道的。感謝您鏈接到文檔。 –

相關問題