我不建议只在新控制器中使用 window.location.href ,因为 ngRoute 会将历史记录设置为指向不存在的页面(因此当用户单击返回时,它将继续重定向到 404页)。我试过了,但失败了。
我想在这里向您指出我对另一个 SO 问题的相关解决方案:
https ://stackoverflow.com/a/27938693/1863794
我采用了它并应用于您的场景。我不认为MainCtrl
在 ng-view 之外使用它是一个坏主意,因为它只会被声明一次,除非你有嵌套的 ng-view 层......我也没有看到任何代码重复,你如果 MainCtrl 非常困扰您,可以将 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;
});
}
});
}
]);
干杯