Direct AngularJS to automatically reroute users from the login page to the welcome page

I am currently developing a web application where I need to redirect from the login page to the welcome page once the user id and password have been validated.

    <script>
    var app = angular.module('myApp', []);
    app.controller('customersCtrl', function ($scope, $http, $interval) {
        //login
        $scope.loginbutton = function () {
            $http.get('/login.asmx/loginuser', {
                params: {
                    log: $scope.log,
                    pm: $scope.pm,
                    password: $scope.password
                }
            })
            .then(function (response) {
                {
                   //Need code here to redirect to another page
                }
            })
        }
    });
</script>

This script showcases my use of AngularJS. How can I successfully redirect to another page using this script?

Answer №1

To navigate in AngularJS, you can utilize the $location service like this:

<br>$location.path('/home')<br>

If you need more details, refer to the official documentation provided.

Answer №2

To include $window in your controller, follow these steps:

app.controller('customersCtrl', function ($scope, $http, $interval, $location, $window) {

Next, make sure to insert the following line inside your response function:

.then(function (response) 
                {
                    $window.location.href = "../welcome/Index";
                }
            })

Answer №3

<script>
    var app = angular.module('myApp', ['$location']);
    app.controller('customersCtrl', function ($scope, $http, $interval, $location) { // including $location as a dependency
      
        $scope.loginbutton = function () {
            $http.get('/login.asmx/loginuser', {
                params: {
                    log: $scope.log,
                    pm: $scope.pm,
                    password: $scope.password
                }
            })
            .then(function (response) {
                {
                    $location.path('google.com') // passing the URL as a parameter
                }
            })
        }
    });
</script>

Answer №4

Utilize the $state parameter for redirection.

controller.js

controller('customersCtrl', function ($scope, $http, $interval, $state) {
    $scope.loginbutton = function () {
        $http.get('/login.asmx/loginuser', {
            params: {
                log: $scope.log,
                pm: $scope.pm,
                password: $scope.password
            }
        })
        .then(function (response) {
             $state.go('page');
        })
    }
});

In the route.js file, specify the new state to which you want to redirect.

angular.module('app.routes', []);
    .config(function($stateProvider, $urlRouterProvider) {

    $stateProvider

        .state('page', {
            url: '/page',
            templateUrl: 'templates/page.html',
            controller: 'pageCtrl'
       })
});

Answer №5

To redirect to the login page, ensure that you have included the $location dependency in your controller and added the code $location.url('/login'). I have made the necessary modifications to your code for this purpose.

<script>
    var app = angular.module('myApp', []);
    app.controller('customersCtrl', function ($scope, $http, $interval, $location) {
        //login
        $scope.loginbutton = function () {
            $http.get('/login.asmx/loginuser', {
                params: {
                    log: $scope.log,
                    pm: $scope.pm,
                    password: $scope.password
                }
            })
            .then(function (response) {
                {
                   //Redirect to welcome page
                   $location.url('/welcome');
                }
            })
        }
    });
</script>

Ensure that you have defined a path for welcome in your route provider as shown below.

(function () {
    'use strict';

    angular.module('myApp', [
        'ngRoute'
    ])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/login', {
            templateUrl: 'views/landing.html',
            controller: 'landingController'
        });
        $routeProvider.when('/customers', {
            templateUrl: 'views/customers.html',
            controller: 'customersCtrl'
        });
        $routeProvider.when('/welcome', {
            templateUrl: 'views/welcome.html',
            controller: 'welcomeController'
        });
        ..............
        ..............
        $routeProvider.otherwise({
            redirectTo: '/login'
        });
    }]);
})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for unit testing an Angular Service that is primarily responsible for redirecting to an external page from the application

My service is responsible for redirecting to a separate login page since we are implementing login as a service. function redirectToMembership() { var returnURL = $location.host(); returnURL+="/#/Authorization"; $window.location.href=Environme ...

Interactive preview of PDFs with pdf.js adaptation

How can I update my PDF preview when resizing the window? Currently, the canvas resizes but the PDF preview remains the same size. I am struggling to find a solution for this. var myState = { pdf: null, currentPage: 1, zoom ...

When trying to access the "form" property of a form ElementRef, TypeScript throws an error

I've encountered an issue with accessing the validity of a form in my template: <form #heroForm="ngForm" (ngSubmit)="onSubmit()"> After adding it as a ViewChild in the controller: @ViewChild('heroForm') heroForm: ElementRef; Trying ...

Retrieve vuex state in a distinct axios template js file

I have encountered an issue with my Vue project. I am using Vuex to manage the state and making axios requests. To handle the axios requests, I created a separate file with a predefined header setup like this: import axios from 'axios' import st ...

Utilizing the forEach method for decision-making

Here is an array called 'array' with values [10, 15, 20] var array = [10, 15, 20]; There is also a variable named N with a value of 20: var N = 20; I need to iterate through the array and check if N is greater than all numbers in the array in ...

Javascript eval function providing inaccurate results

I have encountered a problem while using eval() for a calculator I am developing. When I input the following code: console.log(eval("5.2-5")); The output is: 0.20000000000000018 I am confused as to why this is happening. Thank you for your assistance. ...

JavaScript functions do not work within the HTML code

I am currently working on my debut website and I'm facing an issue with the JavaScript file not functioning properly. Is there a chance you can help me troubleshoot this? I'm still in the learning stages of programming. This is the HTML content ...

How to dynamically delete React Router Link components after they have been clicked on?

When using React Router, how do I remove the div that contains a Link component or the Link component itself when it is clicked on and the routing is complete? For instance, consider an app structured in the following way: ==Header== ==Link1 Link2== Onc ...

Issue with setTimeout() function not being triggered within a VueJS method

I am currently developing an application that allows a user to reset or shutdown a particular server. I am focused on creating the interface and ensuring that the user receives appropriate messages about the actions being taken. My approach involves displa ...

Open a webpage and execute JavaScript with just one click of a bookmark

I found a convenient bookmark that opens my Google Calendar page at http://www.google.com/calendar/renderOnline. Additionally, I have another bookmarklet that applies specific JavaScript to the page: javascript:document.getElementById('gadgetcell&apo ...

I encountered a parsing issue while trying to compile my Vue project

Issue: The component name "Header" should always consist of multiple words. Fix: Change the component name to a multi-word format according to Vue standards (vue/multi-word-component-names). ...

angular8StylePreprocessorSettings

I'm currently trying to implement the approach found on this tutorial in order to import scss files through stylePreprocessorOptions in Angular 8. However, I'm encountering an error stating that the file cannot be found. Any suggestions on how to ...

Performing an action once all AJAX requests have finished

I'm dealing with a situation where I have a click event triggering 3 ajax calls: $("#button").click(function(e) { e.preventDefault(); $.ajax(call1); $.ajax(call2); $.ajax(call3); some_function() //needs to be executed only afte ...

Is it possible to use AngularJS promise scheduling with `async`/`await` syntax?

When working with AngularJS services, TypeScript often recommends that I switch my code to use async/await functions. https://i.sstatic.net/vks1i.png While I understand that using the await keyword is compatible with third-party promises because it essen ...

Creating a sorting function in VueJS requires a few key steps

I'm working on implementing a sorting function in my VueJS code that includes the following options: Price: Low to High, Price: High to Low. Here is my template: <div name="divSortBy"> <span> Sort by: & ...

JavaScript makes it simple to display student names based on their ID numbers

Here is my JavaScript code: <script language="Javascript"> var data = { 7: "Jack Black", 8: "John Smith" }; var id = document.getElementById("id"), emp = document.getElementById("name"); id.addEventListener("keyup", function() { emp.value ...

"Failed authentication for client" in the testing environment of PayPal sandbox

I obtained the code from github and updated the Client ID & App Secret accordingly. It worked flawlessly. https://github.com/paypal-examples/docs-examples/tree/main/advanced-integration However, upon integrating the codes into my project, I encountered th ...

AmCharts Axis renderer mistakenly renders an additional grid line

I have successfully created a basic XYChart using amcharts4. To get rid of the grid lines on the x-axis, I changed the stroke opacity for the x-axis grid to 0 using the following code: xAxis.renderer.grid.template.strokeOpacity = 0; Everything was workin ...

Storing segments of URL data for future use in React applications

Is there a way to extract information from a URL? I wish to utilize the appended details in this URL http://localhost:3000/transaction?transactionId=72U8ALPE within a fetch API. My goal is to retrieve the value 72U8ALPE and store it either in a state var ...

No error reported upon trying to render json output

I'm having an issue where the following code is not displaying any output. Can someone help me identify what mistake I might be making? This is the HTML file: <head> <script type = "text/javascript"> function ajax_get_json() { var h ...