Angularjs $scope 里面的$apply 方法 和 $watch 方法
2016-11-12 17:31
567 查看
Angularjs scope里面的apply 方法 和 watch方法学习要点:1.Angularjsscope 里面的apply方法2.Angularjsscope 里面的watch方法1.Angularjsscope 里面的$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>
相关文章推荐
- AngularJs $scope 里面的$apply 方法和$watch方法
- Angularjs $scope 里面的$apply 方法 和 $watch 方法
- AngularJS $scope里面的$apply方法和$watch方法
- Angularjs $scope 里面的$apply方法 和 $watch方法
- 【AngularJS】4.AngularJS $scope里面的$apply方法和$watch方法
- angularJS<六、$scope里的$watch方法>
- angularJS $scope的$watch方法监听model改变
- angularjs $scope.$apply 方法详解
- angularjs $scope.$apply 方法详解
- angularJS<六、$scope里的$watch方法>
- AngularJs directive-scope双向绑定方法处理-实例2
- AngularJS and scope.$apply
- 浅谈angular.js中实现双向绑定的方法$watch $digest $apply
- angularJS $scope的$apply方法实现model刷新
- [转载]AngularJS and scope.$apply
- AngularJs $scope.$apply
- Angular项目中$scope.$apply()方法的使用详解
- 浅谈angular.js中实现双向绑定的方法$watch $digest $apply
- AngularJS and scope.$apply
- angularjs $scope.$apply()