我正在尝试按照AngularJS 自己的教程学习 AngularJS 的视图和路由机制。
我的问题是本教程将其所有控制器都声明在全局范围内,我认为这是一种不好的做法,因为我们在添加更多控制器时会污染它。
这是我能够按照上述教程构建的快速工作页面(也有一个小提琴):
<!doctype html>
<html>
<head>
<title>Test</title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.1/angular.js"></script>
<script>
"use strict";
var MyFirstController = function ($scope) {
// Do something here.
};
var MySecondController = function ($scope) {
// Do something here.
};
var myModule = angular.module("MyModule", []);
myModule.config(["$routeProvider", function ($routeProvider) {
$routeProvider.when("/first-page", {
template: "<p>My first controller.</p>",
controller: MyFirstController
});
$routeProvider.when("/second-page", {
template: "<p>My second controller.</p>",
controller: MySecondController
});
}]);
$(document).ready(function () {
angular.bootstrap(document, ["MyModule"]);
});
</script>
</head>
<body>
<h1>Test</h1>
<div data-ng-view></div>
<p><a href="#/first-page">Click me!</a></p>
<p><a href="#/second-page">Click me too!</a></p>
</body>
</html>
天真的,我试图在模块内移动控制器:
myModule.config(["$routeProvider", function ($routeProvider) {
$routeProvider.when("/first-page", {
template: "<p>My first controller.</p>",
controller: MyFirstController
});
$routeProvider.when("/second-page", {
template: "<p>My second controller.</p>",
controller: MySecondController
});
}]);
myModule.controller("MyFirstController", ["$scope", function ($scope) {
// Do something here.
}]);
myModule.controller("MySecondController", ["$scope", function ($scope) {
// Do something here.
}]);
唉,它(显然)不起作用,抛出ReferenceError: MyFirstController is not defined
异常。
如何让 AngularJS 模块在自己的路由配置中使用自己的控制器?