Redirect to another page on click in AngularJS

In this tute, we will discuss how to redirect to another page on click in AngularJS. For this, we will be using a $scope object, and a service named $window.

If you don’t know what is Scope in AngularJS, $scope is a built-in AngularJS object. It contains application data and methods. It holds the view and controller together and facilitates data transfer between the view and controller. Visit AngularJS documentation to learn more about this.

react view source controller

 

A note on Window service is that it is provided by AngularJS. It is similar to the global window object of the browser. It acts as a wrapper around the global window object.

Redirect to another page in AngularJS

HTML snippet,

<div ng-app="MyApp" ng-controller="MyController">

  <button ng-click="redirect()">Redirect me!</button>
  
</div>

Here, the div element acts as the AngularJS app as well as the controller. The ng-click directive tells what to do when the button(here) is pressed. In this case, it calls the redirect() method.

Angular JS script,

<script>
  var app = angular.module('MyApp', []);
  app.controller('MyController', function($scope, $window) {
    
    $scope.redirect = function(){
      
      var url = "https://codespeedy.com/";
      $window.location.href = url;
    }
  });
</script>

Firstly, the AngularJS app is defined and then, the controller’s objects are elaborated. Since the $window service acts as a wrapper around the global window object, we can use it as a replacement of the window object. We can change the URL manually or use an input tag to get the URL from the user.

Also, read:

As you can see, in JavaScript DOM, the process of redirecting is the same. Here we did it just by using the AngularJS scope to make it happened on clicking a button.

Leave a Reply

Your email address will not be published. Required fields are marked *