Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

javascript - Using $routeProvider to redirect to routes outside of Angular

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...