马丁的回答很好,但我宁愿用以下方法解决问题ui-路由器模块 https://github.com/angular-ui/ui-router:
- 创建三种状态:
root
, dashboard
and landing
.
- 捕获 URL 使用
root
状态并重定向到dashboard
or landing
取决于授权状态。
-
dashboard
and landing
将会有controller
and templateUrl
与其他应用程序状态一起定义在一个地方,这很好。
代码示例:
angular
.module("app", ["ui.router"])
.value("user", {
name: "Bob",
id: 1,
loggedIn: true
})
.config(function($stateProvider) {
$stateProvider
.state("root", {
url: "",
template: "<section ui-view></section>",
controller: function($state, user) {
if ($state.is("root")) $state.go(user.loggedIn ? "dashboard" : "landing");
}
})
.state("landing", {
templateUrl: "landing.html",
controller: "LandingCtrl"
})
.state("dashboard", {
templateUrl: "dashboard.html",
controller: "DashboardCtrl"
});
})
.controller("DashboardCtrl", function($scope, user, $state) {
$scope.logout = function() {
user.loggedIn = false;
$state.go("root");
}
})
.controller("LandingCtrl", function($scope, user, $state) {
$scope.login = function() {
user.loggedIn = true;
$state.go("root");
}
})
Plunker 的完整示例 http://plnkr.co/edit/mAJt6JXEAp1ZdjBC5qsE?p=preview.