在 AngularJS 中使用 $window 或 $location 重定向

我正在开发的应用程序包含各种状态(使用 ui-router) ,其中一些状态要求您登录,其他状态是公开可用的。

我已经创建了一个方法,可以有效地检查用户是否已经登录,我目前遇到的问题实际上是在必要时重定向到我们的登录页面。应该注意的是,登录页面目前没有放在 AngularJS 应用程序中。

app.run(function ($rootScope, $location, $window) {


$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {


if (toState.data.loginReq && !$rootScope.me.loggedIn) {
var landingUrl = $window.location.host + "/login";
console.log(landingUrl);
$window.open(landingUrl, "_self");
}
});
});

Log 正确地显示了预期的 URL。在这之后,我尝试了几乎所有的方法,从 $window.open 到 window.location.href,不管我尝试什么,都没有发生重定向。

237058 次浏览

I believe the way to do this is $location.url('/RouteTo/Login');

Say my route for my login view was /Login, I would say $location.url('/Login') to navigate to that route.

For locations outside of the Angular app (i.e. no route defined), plain old JavaScript will serve:

window.location = "http://www.my-domain.example/login"

It might help you! demo

AngularJs Code-sample

var app = angular.module('urlApp', []);
app.controller('urlCtrl', function ($scope, $log, $window) {
$scope.ClickMeToRedirect = function () {
var url = "http://" + $window.location.host + "/Account/Login";
$log.log(url);
$window.location.href = url;
};
});

HTML Code-sample

<div ng-app="urlApp">
<div ng-controller="urlCtrl">
Redirect to <a href="#" ng-click="ClickMeToRedirect()">Click Me!</a>
</div>
</div>

It seems that for full page reload $window.location.href is the preferred way.

It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href.

https://docs.angularjs.org/guide/$location

You have to put:

<html ng-app="urlApp" ng-controller="urlCtrl">

This way the angular function can access into "window" object

Not sure from what version, but I use 1.3.14 and you can just use:

window.location.href = '/employee/1';

No need to inject $location or $window in the controller and no need to get the current host address.