使用 $routeProvider 重定向到 Angular 之外的路由 [英] Using $routeProvider to redirect to routes outside of Angular

查看:29
本文介绍了使用 $routeProvider 重定向到 Angular 之外的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Angular 编写了一个 Web 应用程序的一部分.为了确保覆盖所有路由,我想在 $routeProvider 中添加一个 redirectTo 属性,以便将无效路由返回到 Web 应用程序的根目录,这不会不要使用 Angular.

我试过了:

$routeProvider.otherwise({重定向到:'/'});

但显然这仅在 URL 的 Angular 控制部分路由,因此用户将被重定向到类似 http://app.com/angular-part-of-web-app#,而不是 http://app.com,我希望他们去的地方.

我已经解决了这个问题,将一个空白部分用作404"页面,然后使用一个仅使用 $window 对象重定向到所需页面的控制器:

routes.js

//重定向到站点列表.$routeProvider.when('/404', {templateUrl: '/partials/404.html',控制器:'RedirectCtrl'});//重定向到 404 页面.$routeProvider.otherwise({重定向到:'/404'});

controllers.js

//将用户重定向到站点根页面的控制器..controller('RedirectCtrl', ['$scope', '$window', function ($scope, $window) {$window.location.href = '/';}]);

然而,这引发了太黑了,必须有更好的方法"的警钟.在 Angular 中是否有更好的方法来做到这一点?

Angular 路由 - 重定向到外部站点? 没有给出相同问题的答案.我将让我的问题保持开放,而不是将其标记为重复(目前),因为 Angular 世界发展如此之快,以前的答案可能不再如此.

解决方案

上述带有/404 的解决方案对我不起作用.然而,这似乎有效

.否则({控制器:函数(){window.location.replace('/');},模板:<div></div>"});

附注.我正在使用 Angular 1.2.10

I've written part of a web application in Angular. To ensure that all routes are covered, I wanted to add a redirectTo property to the $routeProvider, so that invalid routes are returned to the root of the web application, which doesn't use Angular.

I tried:

$routeProvider.otherwise({
    redirectTo: '/'
});

but obviously this only routes in the Angular controlled portion of the URL, so users would be redirected to a URL like http://app.com/angular-part-of-web-app#, instead of http://app.com, where I'd like them to go.

I've worked around this by having a blank partial to act as a '404' page, and then a controller which just uses the $window object to redirect to the desired page:

routes.js

// Redirect to site list.
$routeProvider.when('/404', {
    templateUrl: '/partials/404.html',
    controller: 'RedirectCtrl'
});

// Redirect to the 404 page.
$routeProvider.otherwise({
    redirectTo: '/404'
});

controllers.js

// Controller to redirect users to root page of site.
.controller('RedirectCtrl', ['$scope', '$window', function ($scope, $window) {

    $window.location.href = '/';
}]);

However, this is setting off the 'too hacky, must be a better way' alarm bells. Is there a better way to do this in Angular?

EDIT: Angular routes - redirecting to an external site? didn't yield an answer to the same question. I'm going to leave my question open instead of marking it as a duplicate (for now), as with the Angular world moving so fast, the previous answer may no longer be the case.

解决方案

The above solution with /404 does not work for me. This however seems to work

.otherwise({
    controller : function(){
        window.location.replace('/');
    }, 
    template : "<div></div>"
});

PS. I am using Angular 1.2.10

这篇关于使用 $routeProvider 重定向到 Angular 之外的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆