如何在ng-view外设置信息到index.html
How to set information into index.html outside the ng-view
我是第一次使用 angular,在 index.html 文件中显示一些动态信息时遇到了一些问题。 ng-view 标签内的所有内容都运行良好。
当用户进行身份验证时,一个包含用户信息的全局变量将被放入 $rootScope 和 cookie 中。我试图通过执行类似 {{$rootScope.globals.currentUser.username}} 的操作来访问索引中的 $rootScope,但它不起作用。所以考虑下面的代码,如何在 index.html?
中显示登录的用户信息
我尝试在我的 app.js 中创建一个控制器并将 ng-controller 放在 body 上。虽然这有效,但它不会在用户注销时刷新(需要刷新页面以更新应用程序控制器)。用户登录后也会发生同样的情况(需要刷新整个页面才能显示信息)。
设置 cookie 的代码和 $rootScope 中的 object。
function SetCredentials(username, password, token) {
$rootScope.globals = {
currentUser: {
username: username,
token: token
}
};
$http.defaults.headers.common['Authorization'] = 'Bearer ' + token;
$cookies.put('globals', JSON.stringify($rootScope.globals));
}
我还有以下 index.html 文件。如您所见,我已经设置了 {{$rootScope.globals.currentUser.username}} 但在用户登录后没有任何显示
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<base href="/" />
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My App</title>
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- css references -->
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<!-- Main Header -->
<header class="main-header">
<!-- Header Navbar -->
<nav class="navbar navbar-static-top" role="navigation">
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<!-- Navbar Right Menu -->
<div class="navbar-custom-menu">
{{$rootScope.globals.currentUser.username}}
</div>
</nav>
</header>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<ng-view></ng-view>
</div>
<!-- /.content-wrapper -->
<!-- Main Footer -->
<footer class="main-footer">
<!-- To the right -->
<div class="pull-right hidden-xs">
something here
</div>
<!-- Default to the left -->
<strong>Copyright © 2016 <a href="#">NPF</a>.</strong> All rights reserved.
</footer>
</div>
<!-- ./wrapper -->
<!-- REQUIRED JS SCRIPTS -->
<!-- jQuery 2.2.0 -->
<script src="Scripts/jquery-2.2.3.js"></script>
<script src="Scripts/bootstrap.js"></script>
<script src="Scripts/app.min.js"></script>
<script src="Scripts/linq.min.js"></script>
<script src="scripts/angular/angular.min.js"></script>
<script src="scripts/angular/angular-route.min.js"></script>
<script src="scripts/angular/angular-resource.min.js"></script>
<script src="scripts/angular/angular-cookies.min.js"></script>
<!-- application scripts -->
<!-- Main app -->
<script src="app/app.js"></script>
<!-- controllers -->
<script src="app/home/home.controller.js"></script>
<!-- services -->
<script src="app/services/authentication.service.js"></script>
<script src="app/services/user.service.js"></script>
</body>
</html>
我的app文件,如下
(function () {
'use strict';
angular
.module('myApp', ['ngRoute', 'ngCookies', 'treeControl'])
.constant("appSettings",
{
serverPath: "http://localhost:64789/",
webApiPath: "http://localhost:64789/api/"
})
.config(config)
.run(run);
config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {
$locationProvider.html5Mode({
enabled: true,
});
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'app/home/home.html',
controllerAs: 'viewModel'
})
.when('/login', {
controller: 'LoginController',
templateUrl: 'app/login/login.html',
controllerAs: 'viewModel'
})
.when('/register', {
controller: 'RegisterController',
templateUrl: 'app/register/register.html',
controllerAs: 'viewModel'
})
.otherwise({ redirectTo: '/login' });
};
run.$inject = ['$rootScope', '$location', '$cookies', '$http'];
function run($rootScope, $location, $cookies, $http) {
// keep user logged in after page refresh
try {
$rootScope.globals = JSON.parse($cookies.get('globals'));
}
catch (err) {
$rootScope.globals = {};
}
if ($rootScope.globals && $rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.globals.currentUser.token;
}
//config.headers.Authorization = 'Bearer ' + authData.token;
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// redirect to login page if not logged in and trying to access a restricted page
var restrictedPage = $.inArray($location.path(), ['/login', '/register', '/gds']) === -1;
try {
var loggedIn = $rootScope.globals.currentUser;
}
catch (err) {
}
if (restrictedPage && !loggedIn) {
$location.path('/login');
}
});
}})();
如我评论中所述,HTML 标记表达式中不需要 $rootScope
。
但是如果您忘记在 ng-view 之外的 HTML 添加控制器,这也可能导致变量未定义。 (没有控制器 = 没有 $scope)
我是第一次使用 angular,在 index.html 文件中显示一些动态信息时遇到了一些问题。 ng-view 标签内的所有内容都运行良好。
当用户进行身份验证时,一个包含用户信息的全局变量将被放入 $rootScope 和 cookie 中。我试图通过执行类似 {{$rootScope.globals.currentUser.username}} 的操作来访问索引中的 $rootScope,但它不起作用。所以考虑下面的代码,如何在 index.html?
中显示登录的用户信息我尝试在我的 app.js 中创建一个控制器并将 ng-controller 放在 body 上。虽然这有效,但它不会在用户注销时刷新(需要刷新页面以更新应用程序控制器)。用户登录后也会发生同样的情况(需要刷新整个页面才能显示信息)。
设置 cookie 的代码和 $rootScope 中的 object。
function SetCredentials(username, password, token) {
$rootScope.globals = {
currentUser: {
username: username,
token: token
}
};
$http.defaults.headers.common['Authorization'] = 'Bearer ' + token;
$cookies.put('globals', JSON.stringify($rootScope.globals));
}
我还有以下 index.html 文件。如您所见,我已经设置了 {{$rootScope.globals.currentUser.username}} 但在用户登录后没有任何显示
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<base href="/" />
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My App</title>
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- css references -->
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<!-- Main Header -->
<header class="main-header">
<!-- Header Navbar -->
<nav class="navbar navbar-static-top" role="navigation">
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<!-- Navbar Right Menu -->
<div class="navbar-custom-menu">
{{$rootScope.globals.currentUser.username}}
</div>
</nav>
</header>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<ng-view></ng-view>
</div>
<!-- /.content-wrapper -->
<!-- Main Footer -->
<footer class="main-footer">
<!-- To the right -->
<div class="pull-right hidden-xs">
something here
</div>
<!-- Default to the left -->
<strong>Copyright © 2016 <a href="#">NPF</a>.</strong> All rights reserved.
</footer>
</div>
<!-- ./wrapper -->
<!-- REQUIRED JS SCRIPTS -->
<!-- jQuery 2.2.0 -->
<script src="Scripts/jquery-2.2.3.js"></script>
<script src="Scripts/bootstrap.js"></script>
<script src="Scripts/app.min.js"></script>
<script src="Scripts/linq.min.js"></script>
<script src="scripts/angular/angular.min.js"></script>
<script src="scripts/angular/angular-route.min.js"></script>
<script src="scripts/angular/angular-resource.min.js"></script>
<script src="scripts/angular/angular-cookies.min.js"></script>
<!-- application scripts -->
<!-- Main app -->
<script src="app/app.js"></script>
<!-- controllers -->
<script src="app/home/home.controller.js"></script>
<!-- services -->
<script src="app/services/authentication.service.js"></script>
<script src="app/services/user.service.js"></script>
</body>
</html>
我的app文件,如下
(function () {
'use strict';
angular
.module('myApp', ['ngRoute', 'ngCookies', 'treeControl'])
.constant("appSettings",
{
serverPath: "http://localhost:64789/",
webApiPath: "http://localhost:64789/api/"
})
.config(config)
.run(run);
config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {
$locationProvider.html5Mode({
enabled: true,
});
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'app/home/home.html',
controllerAs: 'viewModel'
})
.when('/login', {
controller: 'LoginController',
templateUrl: 'app/login/login.html',
controllerAs: 'viewModel'
})
.when('/register', {
controller: 'RegisterController',
templateUrl: 'app/register/register.html',
controllerAs: 'viewModel'
})
.otherwise({ redirectTo: '/login' });
};
run.$inject = ['$rootScope', '$location', '$cookies', '$http'];
function run($rootScope, $location, $cookies, $http) {
// keep user logged in after page refresh
try {
$rootScope.globals = JSON.parse($cookies.get('globals'));
}
catch (err) {
$rootScope.globals = {};
}
if ($rootScope.globals && $rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.globals.currentUser.token;
}
//config.headers.Authorization = 'Bearer ' + authData.token;
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// redirect to login page if not logged in and trying to access a restricted page
var restrictedPage = $.inArray($location.path(), ['/login', '/register', '/gds']) === -1;
try {
var loggedIn = $rootScope.globals.currentUser;
}
catch (err) {
}
if (restrictedPage && !loggedIn) {
$location.path('/login');
}
});
}})();
如我评论中所述,HTML 标记表达式中不需要 $rootScope
。
但是如果您忘记在 ng-view 之外的 HTML 添加控制器,这也可能导致变量未定义。 (没有控制器 = 没有 $scope)