第四讲 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(); }); 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点击事件发生了'; }; }); 2. Angularjs $scope里面的$watch方法 $watch方法作用: $watch方法监视Model的变化。 价格: 个数: 费用:{{ sum() | currency:'¥' }} 运费:{{iphone.fre | currency:'¥'}} 总额:{{ sum() + iphone.fre | currency:'¥'}} 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; }); }); |
Archiver|手机版|小黑屋| PhoneGap中文网 ( 京ICP备13027796号-1 )
GMT+8, 2024-4-20 12:52 , Processed in 0.025382 second(s), 20 queries .
Powered by Discuz! X3.2
© 2001-2013 Comsenz Inc.