刚开始学习angular,没想到写的一个小的demo就出错
代码如下:
<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="UTF-8">
<title></title>
<script src="angular.js"></script>
<!--<script src="controller.js"></script>-->
</head>
<body>
<!--<p>{{'hello word'}}</p>-->
<div ng-controller='HelloController'>
<p>{{greeting.text}}</p>
</div>
<script>
function HelloController($scope){
$scope.greeting = {
text:"hello"
};
}
</script>
</body>
</html>
报了一个这样的错
Argument 'HelloController' is not a function, got undefined
原因是angular没法知道你定义的函数是一个controller,angularJs 1.3 中 为了让 根节点上(rootScope)不再被挂上冗余的内容,
所以禁止了直接在根上注册controller。
所以不能直接使用function XXXcontroller (){ code......}这样的方式直接注册监听器了。以后必须
angular.module('myApp', []).controller('myCtroller',function($scope) {}这样来将controller注册到对应的模型上。
改成这样就没错了
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<title></title>
<script src="angular.js"></script>
</head>
<body>
<!--<p>{{'hello word'}}</p>-->
<div ng-controller='HelloController'>
<p>{{greeting.text}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('HelloController', function ($scope) {
$scope.greeting = {
text: 'hello'
};
})
</script>
</body>
</html>
代码如下:
<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="UTF-8">
<title></title>
<script src="angular.js"></script>
<!--<script src="controller.js"></script>-->
</head>
<body>
<!--<p>{{'hello word'}}</p>-->
<div ng-controller='HelloController'>
<p>{{greeting.text}}</p>
</div>
<script>
function HelloController($scope){
$scope.greeting = {
text:"hello"
};
}
</script>
</body>
</html>
报了一个这样的错
Argument 'HelloController' is not a function, got undefined
原因是angular没法知道你定义的函数是一个controller,angularJs 1.3 中 为了让 根节点上(rootScope)不再被挂上冗余的内容,
所以禁止了直接在根上注册controller。
所以不能直接使用function XXXcontroller (){ code......}这样的方式直接注册监听器了。以后必须
angular.module('myApp', []).controller('myCtroller',function($scope) {}这样来将controller注册到对应的模型上。
改成这样就没错了
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<title></title>
<script src="angular.js"></script>
</head>
<body>
<!--<p>{{'hello word'}}</p>-->
<div ng-controller='HelloController'>
<p>{{greeting.text}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('HelloController', function ($scope) {
$scope.greeting = {
text: 'hello'
};
})
</script>
</body>
</html>