Guide to logging out from a website using AngularJS

I have developed a login page using AngularJS, where I input static username and password. Upon submitting the form, it redirects to a welcome screen. Now, I am looking to implement a logout feature that will transition from the welcome page back to the login page. How can this be achieved with AngularJS?

Below is the code snippet I have written:

.controller("loginController", function($scope, $location, $rootScope){
        $scope.login = function() {
            var user = $scope.username;
            var password = $scope.password;
            var result = $scope.username + $scope.password;
            
            if (user == "admin" && password == 'admin'){
                $rootScope.loggedIn = true;
                $location.path('/welcome');
            } else {
                alert("INVALID CREDENTIALS");
            }
        }

    .controller('welcomeController', function($scope){
        $scope.message = "Welcome here"
    })

Answer №1

Follow the instructions provided by Sajeetharan in a previous response.
Simply clear the values of $scope.username and $scope.password within the logout function.

Create a function that will redirect your page to the home page and include the following code:

.controller('logoutController', function($scope,$location){
  $scope.logout = function(){
      //Clear values from scope
      $scope.username = '';
      $scope.password = '';
      $location.path('/home');
  }
})

Then, call this function using ng-click

<button ng-click="logout()">
  Logout
</button>

By the way, the method you are currently using may not be ideal.

Answer №2

To create a function that redirects your page to the home page, follow these steps:

.controller('redirectController', function($scope,$location){
  $scope.redirectToHomePage = function(){
      $location.path('/home');
  }
})

Next, use ng-click to call this function:

<button ng-click="redirectToHomePage()">
  Go to Home
</button>

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

JavaScript did not apply the style as expected. However, the console displays the information

Utilizing jQuery to add a specific style $("#notifPrefWA").attr('style', "border-radius: 5px; border:#FF0000 5px solid; padding: 10px;"); The style change is visible in the source and console when Chrome inspected... but the ...

Utilize Services without creating circular interdependencies

My app utilizes a GlobalDataService (GDS) to store all data globally. GlobalDataService (GDS) angular .module('app.core') .service('GlobalDataService', GlobalDataService); GlobalDataService.$inject = ['$http&a ...

The data in AngularJS ng-repeat does not appear accurately

I've encountered an unusual issue while working with ng-repeat in combination with ui-router. To test this, I set up a simple markup that fetches data from my local node server and displays it using ng-repeat. During the test, I add a new row to the ...

Executing a for-in loop that iterates through MongoDB operations

I am facing an issue with a function that looks like this... for(key in object){ db.collection.findOne(criteria, function(err, doc){ // ... db.collection.update(...); }) }; The problem is that the value of key keeps changing befor ...

Blend the power of Node's CommonJS with the versatility of Typescript's ES modules

I currently have a Node.js v10 legacy application that was built using CommonJS modules (require). The entire codebase is written in JavaScript. However, I am considering upgrading the app and refactoring a specific part of it to use TypeScript modules ( ...

Content in the <core-animation-pages> element is extending beyond the borders of the main DIV when the "slide-from-right" effect is applied (Polymer

Check out this quick video I made to demonstrate the issue: I have successfully incorporated core-animation-pages into my web application. I have three different divs that transition using the slide-from-right animation without any problems. However, in d ...

I'm looking for the documentation for the latest version of Footable's Events. Can you point me

Does anyone know where to find information on the events that are fired for Footable and how to handle them? I checked the documentation at , but it doesn't provide much detail on events. If you have any resources or suggestions, please let me know! ...

Angular and Laravel API combination for creating a straightforward single page application

I'm looking to develop a straightforward Single Page Application using AngularJS and Laravel 4 as my API backend. The application will consist of basic posts, categories (essentially a blog), and some static pages. My goal is to integrate Laravel&apos ...

Is there a way to access a random element from an array upon pressing a button?

My dilemma involves a reducer array containing Q/A objects that are displayed in two different divs. I want to create a function that will be triggered by the "Next" button, generating a random number to determine which object from the array is displayed n ...

Inject JSON result into an HTML div after an AJAX request

I have successfully implemented a JavaScript AJAX call that returns JSON data, and now I am trying to display it on my HTML page. Here is the code snippet I am using: success: function(response) { console.log(response); for (var i=0; i < response.len ...

Unable to display script in the sources tab on NW.js 16

After updating to the latest version of NW.js (nwjs-sdk-v0.16.1-linux-x64) and attempting to migrate my project over, I encountered a strange issue with debugging. The script I was working on, named "bunny.js", would show up under "Applications" but not in ...

What are some solutions for resolving conflicts between map zoom and page zoom on a mobile website?

My website features a mashup displayed on Google Map. However, I've encountered an issue when trying to zoom into the map on a mobile web browser - more often than not, the page ends up zooming instead of the map itself. Is there a technique in HTML, ...

Adding a new document to MongoDB using the command line interface

For my collection, I need to perform CRUD operations. To streamline this process, I have created a script that handles the insertion of documents into the collection. This script is designed to extract data from a JSON file and insert it into the database ...

Deprecated message received from the body-parser node module

Currently learning Node.js, I've been utilizing the 'express' framework and installed body-parser successfully. However, upon starting my app, I encountered this message from Node: body-parser deprecated bodyParser: use individual json/urle ...

My loop encountered an 'Undefined' error while attempting to retrieve an object from a JSON file

Hey everyone, I could use some help with a problem I'm having in my for loop. The issue is that I keep getting an "undefined" word in the output of my loop. I am trying to retrieve objects from a JSON file and the loop itself seems to be working corre ...

Subscriber client successfully activated and operational via the command line interface

I have incorporated a script into my PHP file that reads the Pusher channel and performs various actions when a new event occurs on the specified channel. If I access the following URL in my browser: http:/localhost/pusher.php and keep it open, the p ...

Step-by-step guide on uploading an image file to a server via $http in Ionic Framework

I am currently utilizing the cordova-plugin-camera for capturing images and sending them to the server along with some attribute values. I have successfully retrieved the image and Image_URI, but I am encountering difficulties in sending it to the server ...

Is there a way to disregard the data returned from previous AJAX calls?

I've been wondering about a strategy for managing delayed AJAX data returns in a scenario where newer calls should take precedence over earlier ones. For instance, if a first data fetch initiated at 12:01:33 is delayed and comes back at 12:01;39, whil ...

Problem encountered when trying to show the Jquery Ajax response on an HTML page

I'm facing a challenge with loading a page that needs to display values with dynamic pagination. To retrieve these values, I am making a REST call which returns a JSON object. Although I can see the JSON output in the browser console, I am unable to d ...

Creating dynamic columns in AngularJS using ng-repeat

I am currently facing a challenge with displaying a list of products using ng-repeat. The columns of these products change dynamically, but there will always be an id column and a name column present. How can I configure ng-repeat to display the values o ...