角度路由-重定向到外部站点
Angular routes - redirecting to an external site?
在AngularJS路由文件中,有一个otherwise
路由选项,取代404:
$routeProvider
.when(...)
.otherwise({
redirectTo: 'my/path'
});
有没有一种方法可以做到这一点,从而将重定向到不在应用程序中的页面?我试过
$routeProvider
.when(...)
.otherwise({
redirectTo: 'http://example.com'
});
但这个jsut试图重定向到我的应用程序中的那个路径,但这个路径并不存在。我知道的解决方案是在顶级控制器中的$scope.$on('$routeChangeStart')
中进行手动重定向,但这是大量的代码重复(而且很难看)。有更好的方法吗?
据我所知,这是不可能的,因为routeProvider
只处理内部路由。
不过你能做的是
$routeProvider
.when(...)
.otherwise({
controller: "404Controller",
template: "<div></div>"
});
然后在控制器中仅使用CCD_ 4。
在我的案例中,这对我很有效:
$routeProvider
.when('/my-path', {
...typical settings...
}).
.otherwise({
redirectTo: function(obj, requestedPath) {
window.location.href = appConfig.url404;
}
});
只需看看angular.js链接行为-禁用特定URL的深度链接
并使用这个
target="_self"
<a href="link" target="_self" >link</a>
我不建议像其他答案中指出的那样在新控制器中使用window.location.href,因为ngRoute会将历史记录设置为指向不存在的页面(因此当用户单击返回时,它将继续重定向到404页面)。我试过了,但失败了。
我想在这里向您介绍我对另一个SO问题的相关解决方案:https://stackoverflow.com/a/27938693/1863794
我采用了这一点,并将其应用于你的场景。我认为在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;
});
}
});
}
]);
干杯
相关文章:
- 火灾在卸载前确认警报仅适用于外部站点
- Cordova/Phonegap在主要的Cordova网络视图中加载外部站点
- Javascript从外部站点获取html
- Javascript或JQuery从外部站点获取html内容
- 使用JavaScript从外部站点解析json
- 当我将javascript代码放在外部站点.js文件中时,Ajax页面方法不起作用
- Javascript - 预填充 cookie 信息,以在指向外部站点的链接上交叉传递不必要的登录页面
- 如何使用Javascript知道页面访问者的IP地址,而无需使用任何外部站点/响应程序
- 显示来自外部站点的 html
- 运行查询并从外部站点检索 XML
- 如果命令嵌入在外部站点中,如何运行函数 cordova
- JQuery 移动版 - 链接到外部站点,无法使用浏览器后退按钮返回页面
- 在 Javascript 或 Jquery 的 Iframe 中出现外部站点的 URL 时出错
- Cordova/AngularJS UI-Router 包装外部站点,没有 iFrame
- 来自一个外部站点的 Javascript 应用程序不在 iframe 中运行
- 如何从 cordova 应用程序内的外部站点获取数据
- 来自外部站点的图像的回退 img src
- JavaScript - 检测外部站点协议 - 客户端
- 在c中按下一个按钮,打开两个新的窗口/选项卡(不同的外部站点)
- 角度路由-重定向到外部站点