Angularjs $scope 裡面的$apply 方法 和 $watch 方法

來源:互聯網
上載者:User

Angularjs $scope 裡面的$apply 方法 和 $watch 方法
Angularjs $scope 裡面的$apply 方法 和 $watch 方法學習要點:1. Angularjs $scope 裡面的$apply 方法2. Angularjs $scope 裡面的$watch 方法1. Angularjs $scope 裡面的$apply 方法$apply 方法作用:Scope 提供$apply 方法傳播 Model 的變化$apply 方法使用情景:AngularJS 外部的控制器( DOM 事件、外部的回呼函數如 jQuery UI 空間等)調用了 AngularJS 函數之後,必須調用$apply。在這種情況下,你需要命令 AngularJS 重新整理自已(模型、視圖等), $apply 就是用來做這件事情的。$apply 方法注意事項:只要可以,請把要執行的代碼和函數傳遞給$apply 去執行,而不要自已執行那些函數然後再調用$apply。例如,你應該像下面這樣來執行你的代碼:$scope.$apply(function() {$scope.variable1 = 'some value';executeSomeAction();});<script type="text/javascript">var app = angular.module("myApp", []);app.controller('firstController',function($scope){$scope.name = 'hello';setTimeout(function(){//$scope.name = 'hi';$scope.$apply(function(){$scope.name = 'hi';});},2000);/*$timeout(function(){$scope.name = 'hi';},2000);*/$scope.show = function(){$scope.name = 'hi 點擊事件發生了';};});</script>2. Angularjs $scope 裡面的$watch 方法$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="CartController"><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('CartController',function($scope){$scope.iphone = {money : 5,num : 1,fre : 10};$scope.sum = function(){return $scope.iphone.money * $scope.iphone.num;};/*$scope.$watch('iphone.money',function(newVal,oldVal){console.log(newVal);console.log(oldVal);},true);*/$scope.$watch($scope.sum,function(newVal,oldVal){//console.log(newVal);//console.log(oldVal);$scope.iphone.fre = newVal >= 100 ? 0 : 10;});});</script></body></html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.