最近在读《Angular JS权威教程》读到第9页,按着示例做,居然报错,说MyController undefined,初学者不懂啊,找了个官方的文档,按着改了一下,貌似成功了,有需要的朋友参考一下,并且帮忙解释一下为啥书上的示例undefined了?
原著:
修改后:
<!doctype html>
<html ng-app="MyApp">
<head>
<title>Hello World</title>
<script type="text/javascript" src="/Users/gongcen/MyPrograms/AngularJS/angular.js"></script>
</head>
<body>
<script type="text/javascript" src="app.js"></script>
<div ng-controller="MyController">
<h1>Hello {{ clock.now }}</h1>
</div>
</body>
</html>
app.js
var MyApp = angular.module('MyApp', []);
MyApp.controller("MyController", function ($scope) {
var updateClock;
if($scope) {
$scope.clock = {
now : new Date()
}
updateClock = function(){
$scope.clock.now = new Date();
};
setInterval(function(){
$scope.$apply(updateClock);
}, 1000);
updateClock();
}
});
结果: