《Angular权威教程》读书笔记1

开始学AngularJs了,正在读《Angular权威教程》。

学习AngularJs最为郁闷的事情就是AngularJs的版本。书里,还有很多网上的例子,经常在较新的版本里就跑不起来了,因此开个贴,边读边改,把书中的例子改到1.4.1可用。

《Angular权威教程》第二章第7页:

原代码在1.2X上可运行:

 1 <!DOCTYPE html>
 2 <html ng-app> 
 3 <head> 
 4     <script src="http://cdn.bootcss.com/angular.js/1.2.0rc3/angular.min.js"></script>
 5 </head>
 6 <body>   
 7     <div ng-controller="MyController">    
 8     <h1>Hello {{ clock }}!</h1> 
 9 </div>   
10 <script type="text/javascript"> 
11     function MyController($scope, $timeout) { 
12         var updateClock = function() { 
13         $scope.clock = new Date();
14         $timeout(function() { 
15                 updateClock();}, 1000);
16         };   
17         updateClock();
18     }; 
19 </script>  
20 </body> 
21 </html> 

在1.3X之后报错:Argument 'MyController' is not a function, got undefined

原因:With angular 1.3+ you can no longer use global controller declaration on the global scope (Without explicit registration). You would need to register the controller using module.controller syntax.

从Angular 1.3X开始,不能使用在全局scope内的全局控制器声明(没有显式注册),要使用module.controller语法来注册控制器。

修改版本:

 1 <!DOCTYPE html>
 2 <html ng-app="MyApp">
 3 <head>
 4     <title>Chap2P7</title>
 5 </head>
 6 <body>
 7 <div ng-controller="MyController">
 8     <h1>Hello <span ng-bind="clock"></span></h1>
 9 </div>
10 <script src="http://cdn.bootcss.com/angular.js/1.4.1/angular.min.js"></script>
11 <script type="text/javascript">
12     var myApp = angular.module('MyApp', []);
13     myApp.controller("MyController", function($scope, $timeout){
14            var updateClock = function() {                
15         $scope.clock = (new Date).toLocaleString()
16         $timeout(function() { 
17                 updateClock();}, 1000);
18         };   
19         updateClock();
20 });
21 </script>
22 </body>
23 </html>

 

posted @ 2015-07-07 10:10  熊白白  阅读(676)  评论(0编辑  收藏  举报