$window or $location to Redirect URL in AngularJs

Redirect to new Page using $location or $window in AngularJs

$window or $location to Redirect URL in AngularJs

Hello everyone, I am going to share the very interesting code-sample for Redirect to another page using $window or $location in AngularJs just like "window.location " or "window.location.href" in the JavaScript.

In the Angular, we are using to $window or $location to achieve this functionality. i.e.

$window.location.href = "http://" + host + "/user/anilsingh581";

The Example in detail as given below.

The AngularJs code-sample

var app = angular.module('RedirectURLApp', []);
    app.controller('RedirectURLCtrl', function ($scope, $log, $window) {
        $scope.name = 'Anil';

    //Click method to call for redirect to URL.
        $scope.RedirectToURL = function () {
            var host = $window.location.host;
            var landingUrl = "http://" + host + "/user/anilsingh581";

            $log.log(landingUrl); //Go Console window and see the logs detail.

            $window.location.href = landingUrl; //Redirect to given URLs.
        };
    });

The HTML code-sample

<div ng-app="RedirectURLApp">
    <div ng-controller="RedirectURLCtrl">
        <h2>$window or $location to Redirect URL in AngularJS</h2>
        <p>Hello {{name}},</p>
        Click to Redirect <a href="#" ng-click="RedirectToURL()">Click Me!</a>
    </div>
</div>

The Full Live example (HTML + Angular) code-sample

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>$window or $location to Redirect URL in AngularJS</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://code.angularjs.org/1.4.1/angular.js"></script>
    <script>
    var app = angular.module('RedirectURLApp', []);
    app.controller('RedirectURLCtrl', function ($scope, $log, $window) {
        $scope.name = 'Anil';

        $scope.RedirectToURL = function () {
            var host = $window.location.host;
            var landingUrl = "http://" + host + "/user/anilsingh581";
            $log.log(landingUrl);
            $window.location.href = landingUrl;
        };
    });
    </script>
</head>
<body ng-app="RedirectURLApp">
    <div ng-controller="RedirectURLCtrl">
        <h2>$window or $location to Redirect URL in AngularJS</h2>
        <p>Hello {{name}},</p>
        Click to Redirect <a href="#" ng-click="RedirectToURL()">Click Me!</a>
    </div>
</body>
</html>

The output, Example,

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.