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,