我正在阅读
https://www.syncfusion.com/resources/techportal/ebooks/angularjs
本书中关于控制器基本用法的第三个样本对我来说不起作用:
JS:
function MyCtrl($scope) {
$scope.visible = true;
$scope.toggle = function() { $scope.visible = !$scope.visible; };
};
HTML:
<html>
<head>
<script src="scripts/vendor/angular/angular.min.js"></script>
<script src="scripts/controllers/app.js"></script>
</head>
<body ng-app>
<div ng-controller="MyCtrl"> <button ng-click="toggle()">Toggle</button>
<p ng-show="visible">Hello World!</p>
</div>
</body>
</html>
错误:
[ng:areq] http://errors.angularjs.org/1.3.0-rc.4/ng/areq?p0=MyCtrl&p1=not%20a%20function%2C%20got%20undefined
Angular对控制器并不满意,不知道我是否正确使用它或者这本书已经过时了?在Angular网站上,我看到了更为复杂的控制器声明的样本。
答案 0 :(得分:3)
您遗漏了一些内容,请参阅下面的代码段
var app=angular.module('app', [])
app.controller('MyCtrl',MyCtrl);
function MyCtrl($scope) {
$scope.visible = true;
$scope.toggle = function() { $scope.visible = !$scope.visible; };
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<head>
<script src="scripts/vendor/angular/angular.min.js"></script>
<script src="scripts/controllers/app.js"></script>
</head>
<body ng-app="app">
<div ng-controller="MyCtrl"> <button ng-click="toggle()">Toggle</button>
<p ng-show="visible">Hello World!</p>
</div>
</body>
</html>
答案 1 :(得分:3)
从版本开始(当然在1.3.0-x上),Angular要求您明确允许将控制器声明为全局函数。请参阅the docs for the $controllerProvider。
allowGlobals();
如果被调用,允许$ controller在窗口
上找到控制器构造函数
所以,你的解决方案是:
angular.module("...", []).config(["$controllerProvider", function($controllerProvider) {
$controllerProvider.allowGlobals();
}]);
上面的模块有被调用,所以它是你的主模块或主模块应该依赖它。
答案 2 :(得分:1)
在开始时粘贴控制器和模板有点棘手。 @sss展示了它是如何完成的。 要检查其他所有内容是否合理,您可以将脚本放入html页面。注意,这只是用于调试,我意识到这不是你想要的。只是初学者的提示:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.8/angular.js"></script>
</head>
<body ng-app>
<script>
function MyCtrl($scope) {
$scope.visible = true;
$scope.toggle = function() { $scope.visible = !$scope.visible; };
};
</script>
<div ng-controller="MyCtrl"> <button ng-click="toggle()">Toggle</button>
<p ng-show="visible">Hello World!</p>
</div>
</body>
</html>
答案 3 :(得分:1)
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
}]);
<html>
<head>
<script src="scripts/vendor/angular/angular.min.js"></script>
<script src="scripts/controllers/app.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="GreetingController">
{{ greeting }}
</div>
</body>
您错过了var myApp = angular.module('myApp',[]);
和<body ng-app="myapp">
,我建议您仔细阅读angular docs。