【发布时间】:2013-10-19 17:56:49
【问题描述】:
我已经用 Angular 编写了 Web 应用程序的一部分。为了确保覆盖所有路由,我想在$routeProvider 中添加一个redirectTo 属性,以便将无效路由返回到不使用Angular 的Web 应用程序的根目录。
我试过了:
$routeProvider.otherwise({
redirectTo: '/'
});
但显然这只路由在 URL 的 Angular 控制部分中,因此用户将被重定向到像 http://app.com/angular-part-of-web-app# 这样的 URL,而不是我希望他们去的 http://app.com。
我已经解决了这个问题,将一个空白部分用作“404”页面,然后使用一个仅使用 $window 对象重定向到所需页面的控制器:
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 = '/';
}]);
但是,这已经敲响了“太老套,必须是更好的方法”的警钟。在 Angular 中有没有更好的方法来做到这一点?
编辑:Angular routes - redirecting to an external site? 没有给出相同问题的答案。我将保留我的问题,而不是将其标记为重复(现在),因为 Angular 世界发展如此之快,以前的答案可能不再是这种情况。
【问题讨论】:
-
可能在服务器端处理它。
-
我也想解决这个问题。我正在将我的应用程序切换到 Angular 并且有一些仍然从服务器提供的部分。需要找到一种方法来连接 Angular 部分和非 Angular 部分
标签: javascript angularjs