[javascript] Using $window or $location to Redirect in AngularJS

The app I am working on contains various states (using ui-router), where some states require you to be logged in, others are publicly available.

I have created a method that validly checks whether a user is logged in, what I am currently having issues with is actually redirecting to our login-page when necessary. It should be noted that the login page is not currently placed within the AngularJS app.

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");
        }
    });
});

The console.log shows the intended url properly. The line after that, I have tried practically everything from $window.open to window.location.href and no matter what I've tried no redirect happens.

EDIT (RESOLVED):

Found the issue.

var landingUrl = $window.location.host + "/login";
$window.open(landingUrl, "_self");

The variable landingUrl was set to 'domain.com/login', which would not work with $window.location.href (which was one of the things I tried). However after changing the code to

var landingUrl = "http://" + $window.location.host + "/login";
$window.location.href = landingUrl;

it now works.

This question is related to javascript angularjs redirect angular-ui-router

The answer is


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.


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>

You have to put:

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

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


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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to redirect

React-Router External link Laravel 5.4 redirection to custom url after login How to redirect to another page in node.js How to redirect to an external URL in Angular2? How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template? Use .htaccess to redirect HTTP to HTTPs How to redirect back to form with input - Laravel 5 Using $window or $location to Redirect in AngularJS yii2 redirect in controller action does not work? Python Requests library redirect new url

Examples related to angular-ui-router

how to refresh page in angular 2 Could not resolve '...' from state '' AngularJS ui router passing data between states without URL What is the difference between $routeProvider and $stateProvider? How to pass parameters using ui-sref in ui-router to controller Exposing the current state name with ui router Clear History and Reload Page on Login/Logout Using Ionic Framework Using $window or $location to Redirect in AngularJS AngularJS UI Router - change url without reloading state `ui-router` $stateParams vs. $state.params