Javascript 角度路由-重定向到外部站点?
在AngularJS路由文件中,有一个Javascript 角度路由-重定向到外部站点?,javascript,angularjs,url-routing,Javascript,Angularjs,Url Routing,在AngularJS路由文件中,有一个或路由选项,替换404: $routeProvider .when(...) .otherwise({ redirectTo: 'my/path' }); 有没有一种方法可以让用户重定向到应用程序中不存在的页面?我试过了 $routeProvider .when(...) .otherwise({ redirectTo: 'http://example.com' }); 但是这个jsut试图重定向到我的应用程序中不存在的路径。我知道的解决
或路由选项,替换404:
$routeProvider
.when(...)
.otherwise({
redirectTo: 'my/path'
});
有没有一种方法可以让用户重定向到应用程序中不存在的页面?我试过了
$routeProvider
.when(...)
.otherwise({
redirectTo: 'http://example.com'
});
但是这个jsut试图重定向到我的应用程序中不存在的路径。我知道的解决方案是在顶级控制器中的$scope.$on(“$routeChangeStart”)
中进行手动重定向,但这是大量代码重复(而且很难看)。有更好的方法吗?对于我的,这是不可能的,因为路由提供程序只处理内部路由
但你能做的是
$routeProvider
.when(...)
.otherwise({
controller: "404Controller",
template: "<div></div>"
});
$routeProvider
.当(…)
.否则({
控制器:“404控制器”,
模板:“”
});
然后只需使用window.location.href=http://yourExternalSite.com/404.html“
在控制器中。我不建议像其他答案中指出的那样在新控制器中使用window.location.href,因为ngRoute会将历史记录设置为指向不存在的页面(所以当用户点击返回时,它将继续重定向到404页面)
我想在这里向大家介绍我对另一个SO问题的相关解决方案:
我采纳了这一点并应用到您的场景中。我认为在ng视图之外使用MainCtrl
并不是一个坏主意,因为除非您有ng视图的嵌套层,否则它只声明一次……我也看不到任何代码重复,如果您非常困扰,可以将MainCtrl放在单独的模块中:
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when(..)
.otherwise({redirectTo: 'http://yourExternalSite.com/404.html'});
}])
.controller('MainCtrl',[ // <- Use this controller outside of the ng-view!
'$rootScope','$window',
function($rootScope,$window){
$rootScope.$on("$routeChangeStart", function (event, next, current) {
// next.$$route <-not set when routed through 'otherwise' since none $route were matched
if (next && !next.$$route) {
event.preventDefault(); // Stops the ngRoute to proceed with all the history state logic
// We have to do it async so that the route callback
// can be cleanly completed first, so $timeout works too
$rootScope.$evalAsync(function() {
// next.redirectTo would equal be 'http://yourExternalSite.com/404.html'
$window.location.href = next.redirectTo;
});
}
});
}
]);
.config(['$routeProvider',函数($routeProvider){
$routeProvider
.何时(……)
。否则({重定向到:'http://yourExternalSite.com/404.html'});
}])
.controller('MainCtrl',[/在我的情况下,这对我来说很有用:
$routeProvider
.when('/my-path', {
...typical settings...
}).
.otherwise({
redirectTo: function(obj, requestedPath) {
window.location.href = appConfig.url404;
}
});
看看
用这个
target=“_self”
正是我想要的。谢谢。适用于angular 1.5此修复程序适用于我(重定向到同一主机上的非angular资源)
<a href="link" target="_self" >link</a>