我正在尝试按照AngularJS' own tutorial学习AngularJS的视图和路由机制。
我的问题是教程在全球范围内声明其所有控制器,我相信这是一种不好的做法,因为我们在添加更多控制器时会污染它。
这是我按照上述教程(a fiddle, too)建立的快速工作页面:
<!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模块在自己的路由配置中使用自己的控制器?
答案 0 :(得分:10)
一旦你知道解决方案,它就非常简单:只需将控制器指定为字符串而不是对象:
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"
});
}]);
这样AngularJS会将控制器名称解析为您在模块中定义的名称。
它也很安全!