AngularJS入门3-小例子-定时器
实现效果:
实现代码:
1 <!DOCTYPE HTML> 2 <html ng-app=""> 3 <head><script src="./angular.min.js"></script></head> 4 <body> 5 <h1>定时器对象</h1> 6 <div ng-controller="ClockController"> 7 <h5>time: {{clock}}</h5> 8 </div> 9 <script type="text/javascript"> 10 function ClockController($scope, $timeout) { 11 var updateClock = function(){ 12 $scope.clock = new Date(); 13 $timeout(function(){ 14 updateClock(); 15 },1000); 16 }; 17 updateClock(); 18 } 19 </script> 20 </body> 21 </html>
改进写法(最佳实践:在视图中通过对象属性而非对象本身来进行引用绑定,是angular中的最佳实践):
1 function ClockController($scope) { 2 $scope.clock ={ 3 now: new Date() 4 }; 5 var updateClock = function(){ 6 $scope.clock.now = new Date(); 7 }; 8 setInterval(function(){ 9 $scope.$apply(updateClock); 10 },1000); 11 12 updateClock(); 13 }