How to redirect to another page using AngularJS?

JavascriptAngularjs

Javascript Problem Overview


I am using ajax call to perform functionality in a service file and if the response is successful, I want to redirect the page to another url. Currently, I am doing this by plain JS code window.location = response['message'];. But I need to replace it with AngularJS code. I have looked various solutions on stackoverflow, they used $location. But I am new to AngularJS and having trouble to implement it.

$http({
            url: RootURL+'app-code/common.service.php',
            method: "POST",
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            dataType: 'json',
            data:data + '&method=signin'

        }).success(function (response) {

            console.log(response);

            if (response['code'] == '420') {

                $scope.message = response['message'];
                $scope.loginPassword = '';
            }
            else if (response['code'] != '200'){

                $scope.message = response['message'];
                $scope.loginPassword = '';
            }
            else {
                window.location = response['message'];
            }
            //  $scope.users = data.users;    // assign  $scope.persons here as promise is resolved here
        })

Javascript Solutions


Solution 1 - Javascript

You can use Angular $window:

$window.location.href = '/index.html';

Example usage in a contoller:

(function () {
    'use strict';

    angular
        .module('app')
        .controller('LoginCtrl', LoginCtrl);

    LoginCtrl.$inject = ['$window', 'loginSrv', 'notify'];

    function LoginCtrl($window, loginSrv, notify) {
        /* jshint validthis:true */
        var vm = this;
        vm.validateUser = function () {
             loginSrv.validateLogin(vm.username, vm.password).then(function (data) {          
                if (data.isValidUser) {    
                    $window.location.href = '/index.html';
                }
                else
                    alert('Login incorrect');
            });
        }
    }
})();

Solution 2 - Javascript

You can redirect to a new URL in different ways.

  1. You can use $window which will also refresh the page
  2. You can "stay inside" the single page app and use $location in which case you can choose between $location.path(YOUR_URL); or $location.url(YOUR_URL);. So the basic difference between the 2 methods is that $location.url() also affects get parameters whilst $location.path() does not.

I would recommend reading the docs on $location and $window so you get a better grasp on the differences between them.

Solution 3 - Javascript

$location.path('/configuration/streaming'); this will work... inject the location service in controller

Solution 4 - Javascript

I used the below code to redirect to new page

$window.location.href = '/foldername/page.html';

and injected $window object in my controller function.

Solution 5 - Javascript

It might help you!!

The AngularJs code-sample

var app = angular.module('app', ['ui.router']);

app.config(function($stateProvider, $urlRouterProvider) {

  // For any unmatched url, send to /index
  $urlRouterProvider.otherwise("/login");

  $stateProvider
    .state('login', {
      url: "/login",
      templateUrl: "login.html",
      controller: "LoginCheckController"
    })
    .state('SuccessPage', {
      url: "/SuccessPage",
      templateUrl: "SuccessPage.html",
      //controller: "LoginCheckController"
    });
});

app.controller('LoginCheckController', ['$scope', '$location', LoginCheckController]);

function LoginCheckController($scope, $location) {

  $scope.users = [{
    UserName: 'chandra',
    Password: 'hello'
  }, {
    UserName: 'Harish',
    Password: 'hi'
  }, {
    UserName: 'Chinthu',
    Password: 'hi'
  }];

  $scope.LoginCheck = function() {
    $location.path("SuccessPage");
  };

  $scope.go = function(path) {
    $location.path("/SuccessPage");
  };
}

Solution 6 - Javascript

In AngularJS you can redirect your form (on submit) to other page by using window.location.href=''; like below:

postData(email){
    if (email=='undefined') {
      this.Utils.showToast('Invalid Email');
    } else {
      var origin = 'Dubai';
      this.download.postEmail(email, origin).then(data => { 
           ...
      });
      window.location.href = "https://www.thesoftdesign.com/";      
    }
  }

Simply try this:

window.location.href = "https://www.thesoftdesign.com/"; 

Solution 7 - Javascript

I faced issues in redirecting to a different page in an angular app as well

You can add the $window as Ewald has suggested in his answer, or if you don't want to add the $window, just add an timeout and it will work!

setTimeout(function () {
		window.location.href = "http://whereeveryouwant.com";
	}, 500);

Solution 8 - Javascript

The simple way I use is

app.controller("Back2Square1Controller", function($scope, $location) {
	window.location.assign(basePath + "/index.html");
});

Solution 9 - Javascript

A good way to do this is using $state.go('statename', {params...}) is faster and more friendly for user experience in cases when you don't have to reload and bootsraping whole app config and stuff

(function() {
    'use strict';

    angular
        .module('app.appcode')
        .controller('YourController', YourController);

    YourController.$inject = ['rootURL', '$scope', '$state', '$http'];

    function YourController(rootURL, $scope, $state, $http) {

        $http({
                url: rootURL + 'app-code/common.service.php',
                method: "POST",
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                dataType: 'json',
                data:data + '&method=signin'

            }).success(function (response) {
                if (response['code'] == '420') {

                    $scope.message = response['message'];
                    $scope.loginPassword = '';
                } else if (response['code'] != '200') {

                    $scope.message = response['message'];
                    $scope.loginPassword = '';
                } else {
                    // $state.go('home'); // select here the route that you want to redirect
                    $state.go(response['state']); // response['state'] should be a route on your app.routes
                }
            })
    }

});

// routes

(function() {
    'use strict';

    angular
        .module('app')
        .config(routes);

    routes.$inject = [
        '$stateProvider',
        '$urlRouterProvider'
    ];

    function routes($stateProvider, $urlRouterProvider) {
        /**
         * Default path for any unmatched url
        */
        $urlRouterProvider.otherwise('/');

        $stateProvider
            .state('home', {
                url: '/',
                templateUrl: '/app/home/home.html',
                controller: 'Home'
            })
            .state('login', {
                url: '/login',
                templateUrl: '/app/login/login.html',
                controller: 'YourController'
            })
            // ... more routes .state
   }

})();

Solution 10 - Javascript

Using location.href="./index.html"

or create scope $window

and using $window.location.href="./index.html"

Solution 11 - Javascript

 (function () {
"use strict";
angular.module("myApp")
       .controller("LoginCtrl", LoginCtrl);

function LoginCtrl($scope, $log, loginSrv, notify) {

    $scope.validateUser = function () {
        loginSrv.validateLogin($scope.username, $scope.password)
            .then(function (data) {
                if (data.isValidUser) {
                    window.location.href = '/index.html';
                }
                else {
                    $log.error("error handler message");
                }
            })
    }
} }());

Solution 12 - Javascript

If you want to use a link then: in the html have:

<button type="button" id="btnOpenLine" class="btn btn-default btn-sm" ng-click="orderMaster.openLineItems()">Order Line Items</button>

in the typescript file

public openLineItems() {
if (this.$stateParams.id == 0) {
    this.Flash.create('warning', "Need to save order!", 3000);
    return
}
this.$window.open('#/orderLineitems/' + this.$stateParams.id);

}

I hope you see this example helpful as it was for me along with the other answers.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFarjad HasanView Question on Stackoverflow
Solution 1 - JavascriptEwald StiegerView Answer on Stackoverflow
Solution 2 - JavascriptCristi BerceanuView Answer on Stackoverflow
Solution 3 - Javascriptuser2266928View Answer on Stackoverflow
Solution 4 - JavascriptSanchi GirotraView Answer on Stackoverflow
Solution 5 - JavascriptAnil SinghView Answer on Stackoverflow
Solution 6 - JavascriptRizwanView Answer on Stackoverflow
Solution 7 - JavascriptVignesh SubramanianView Answer on Stackoverflow
Solution 8 - Javascriptraghavsood33View Answer on Stackoverflow
Solution 9 - JavascriptgsalgadotoledoView Answer on Stackoverflow
Solution 10 - Javascriptshashank raveendranView Answer on Stackoverflow
Solution 11 - JavascriptRuben.sarView Answer on Stackoverflow
Solution 12 - JavascriptNour LababidiView Answer on Stackoverflow