我希望我的 AngularJS 应用程序的根 URL /
能够显示基于 cookie 值的模板。例如,当存在登录 cookie 时,会显示仪表板。当登录 cookie 不存在时,显示登录屏幕。
我尝试将 $cookies 注入(inject)到 app.config
中,以根据它确定 $route
的模板属性,但这不起作用。
var myApp = angular.module('myApp', ['ngRoute', 'ngCookies']);
myApp.config([
'$routeProvider',
'$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
templateUrl: function() {
// read cookies here?
return '../../connect.html';
},
controller: "getAuthUrl"
});
$locationProvider.
html5Mode(true).
hashPrefix('!');
}
]);
最佳答案
回答我自己的问题...
经过进一步调查,我发现 $routeProvider
不是我应该使用的。 $routeProvider
用于基于 URL 路由提供模板。这个问题需要的是ui-router
module,这是一个官方的 AngularJS 模块。
ui-router
可以让您根据“状态”指定页面内容,而不是 URL。在我的情况下,我有一个“登录”状态和一个“仪表板”状态。以下是我实现该解决方案的方法:
var myApp = angular.module('myApp', ['ngCookies', 'ui.router']);
myApp.config([
'$stateProvider',
'$locationProvider',
function ($stateProvider, $locationProvider) {
$stateProvider.
state('login', {
template: '<h1>Login now.</h1>'
}).state('dashboard', {
template: '<h1>You are logged in. Welcome.</h1>'
});
$locationProvider.
html5Mode(true).
hashPrefix('!');
}
]);
myApp.controller('mainCtrl', [
'$scope',
'$state',
'$cookies',
function($scope, $state, $cookies) {
// You can read cookies here
if (true) {
console.log($cookies);
$state.go('dashboard');
}
else {
$state.go('login');
}
}
]);
然后 HTML 是
<!DOCTYPE html>
<html ng-app='myApp'>
<head>
<script src='js/lib/angular.js'></script>
<script src='js/lib/angular-ui-router.js'></script>
<script src='js/lib/angular-cookies.js'></script>
<script src="js/app.js"></script>
</head>
<body ng-controller='mainCtrl'>
<div class="container" ui-view></div>
</body>
</html>
您可以在其 wiki 中阅读有关 ui-router
的所有内容。
注意:您必须至少使用ui-router
v0.0.2。 v0.0.1 无法工作。
关于javascript - 在 AngularJS 中根据 $cookies 值确定路由模板的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18406533/