2014-10-20 22 views
1

這似乎是很簡單,但不工作:由布拉德·格林的書「AngularJS」第一個例子有錯誤

<html ng-app> 
    <head> 
    <script type="text/javascript" src="lib/angular.js"></script> 
    <script type="text/javascript"> 
     function HelloController($scope) { 
     $scope.greeting = { text: 'Hello' }; 
     } 
    </script> 
    </head> 
    <body> 
    <div ng-controller='HelloController'> 
     <p>{{greeting.text}}, World</p> 
    </div> 
    </body> 
</html> 

在屏幕上:

{{greeting.text}}, World 

,並在控制檯:

Error: [ng:areq] Argument 'HelloController' is not a function, got undefined 
http://errors.angularjs.org/1.3.0/ng/areq?p0=HelloController&p1=not%20a%20function%2C%20got%20undefined 
    at http://localhost:8080/lib/angular.js:80:12 
    at assertArg (http://localhost:8080/lib/angular.js:1610:11) 
    at assertArgFn (http://localhost:8080/lib/angular.js:1620:3) 
    at http://localhost:8080/lib/angular.js:8319:9 
    at http://localhost:8080/lib/angular.js:7496:34 
    at forEach (http://localhost:8080/lib/angular.js:343:20) 
    at nodeLinkFn (http://localhost:8080/lib/angular.js:7483:11) 
    at compositeLinkFn (http://localhost:8080/lib/angular.js:6991:13) 
    at compositeLinkFn (http://localhost:8080/lib/angular.js:6994:13) 
    at compositeLinkFn (http://localhost:8080/lib/angular.js:6994:13) 

看不到原因......除了可能是因爲我用AngularJS v1.3.0

+1

不確定關於v1.3.0,但[它適用於v1.2.1](http://jsfiddle.net/rdesai/7rakjukj/)。 [FYI,v1.3.0被列爲不穩定](https://developers.google.com/speed/libraries/devguide?hl=fr#angularjs)。 – 2014-10-20 05:41:24

回答

6

是的,這是因爲1.3.0。 change log描述的突破變化爲:

$控制器將不再尋找窗口上的控制器。爲控制器尋找窗口的舊行爲最初用於示例,演示和玩具應用程序。我們發現允許全局控制器功能鼓勵不良實踐,所以我們決定默認禁用此行爲。

更改日誌接着解釋,你可以重新啓用的「全球性」功能的方法:

雖然我們並不建議你可以重新啓用以前的行爲是這樣的:

angular.module('myModule').config(['$controllerProvider', function($controllerProvider) { 
    // this option might be handy for migrating old apps, but please don't use it 
    // in new ones! 
    $controllerProvider.allowGlobals(); 
}]); 
+0

這實際上是一個非常好的變化。謝謝! – 2014-10-20 05:48:27

1

是的,這是AngularJS 1.3.0的一個問題。規避它的另一種方式(也許更簡單和更安全)是明確包含舊版本的AngularJS。例如:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>

+0

這是一個更好的解決方案,如果你要按照書中的內容和書的進度 – 2015-01-28 19:04:28

1
在角1.4

這是工作溶液:

的index.html

<!DOCTYPE html> 
<html ng-app="testApp"> 
    <head> 
    <title></title> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script> 
    <script src="controllers.js"></script> 
    </head> 
    <body> 
    <div ng-controller='HelloController'> 
     <input ng-model='greeting.text'> 
     <p>{{greeting.text}}, World</p> 
    </div> 
    </body> 
</html>  

controllers.js

var testApp = angular.module('testApp', []); 

testApp.controller('HelloController', function ($scope) { 
    $scope.greeting = { text: 'Hello' }; 
});