javascript 如何使用 Angular.js 进行重定向?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16203602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how can I make a redirection with Angular.js?
提问by hamou92
I want to make a redirection to another route and the page have to be refreshed and treated server side, so the $location.path(url)
can't help me. I have tried window.location(url)
but I have this error: window.location is not a function
我想重定向到另一条路由,并且必须刷新页面并处理服务器端,因此$location.path(url)
无法帮助我。我试过了,window.location(url)
但我有这个错误:window.location is not a function
My app.js:
我的 app.js:
'use strict';
var app = angular.module('myApp', []).
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: 'partials/index'});
$routeProvider.when('/logout', {
controller: 'logoutCtrl'});
$routeProvider.otherwise({
redirectTo: '/'});
$locationProvider.html5Mode(true);
}]);
my logoutCtrl:
我的注销Ctrl:
function logoutCtrl($scope, $location){
$apply(function() {
$location.path("/users/logout");
});
}
The partials/index contains this link:
部分/索引包含此链接:
a(href='/logout') Logout
Now I'm going to show how I manage my routes server side with Express.js:
现在我将展示如何使用 Express.js 管理我的路由服务器端:
app.get('/', ctrl.index);
app.get('/partials/:name', ctrl.partials);
app.get('/users/logout', ctrl.logout);
exports.logout = function(req, res)
{
console.log('logout');
req.session.destroy(function(err){ // I destroy my session
res.redirect('/'); // redirection to '/'
});
}
Now when I click on "logout" nothing happen, I'm just seeing this route localhost:3000/logout
in my bar but if I type localhost:3000/users/logout
I have the result expected (session destroyed and redirection to '/' )
现在,当我点击“注销”时,什么也没有发生,我只是localhost:3000/logout
在我的栏中看到了这条路线,但是如果我输入,localhost:3000/users/logout
我就会得到预期的结果(会话被破坏并重定向到 '/' )
回答by MrMins
With an example of the not working code will be easy to answer this question, but with this > information the best that I can think is that you are calling the $location.path outside of > the angularjs digest.
Try doing this on the directive
scope.$apply(function() {$location.path("/route");});
"
举个不工作代码的例子很容易回答这个问题,但是有了这个 > 信息,我认为最好的是你在 > angularjs 摘要之外调用 $location.path 。
尝试在指令上执行此操作
scope.$apply(function() {$location.path("/route");});
“
回答by Kugel
Just go with:
只是去:
window.location.assign(url);
Alternatively:
或者:
window.location.replace(url);
which doesn't save the current page in browser session history.
它不会在浏览器会话历史记录中保存当前页面。