behavior of the back button within an AngularJS program

Currently facing an issue with a single-page application built using AngularJS. The app is composed of three main views - the login view, main view, and logout view.

  • myapp/#/login
  • myapp/#/main
  • myapp/#/logout

This is my route provider setup:

function Router($routeProvider) {
    $routeProvider
        .when('/login', {
            templateUrl: 'app/components/login/login.tmpl.html',
            controller: 'login.ctrl',
            controllerAs: 'vm'
        })
        .when('/main', {
            templateUrl: 'app/components/dashboard/main.tmpl.html',
            controller: 'dashboard.ctrl',
            controllerAs: 'vm'
        })
        .when('/logout', {
            templateUrl: 'app/components/logout/logout.tmpl.html',
            controller: 'logout.ctrl',
            controllerAs: 'vm'
        })
        .otherwise({
            redirectTo: '/login'
        });
}

Scenario: 1) User logs in. 2) User navigates to the main view to access content. 3) User decides to log out. 4) Confirmation for log out is displayed on the logout view. 5) Upon confirmation, user is redirected back to the login view.

However, upon reaching the login view, clicking the browser's back button leads back to the main view instead of staying on the login view. Is there a way to adjust this behavior specifically for the login view? Any suggestions or insights are greatly appreciated!

Answer №1

To see a functioning example, you can visit: http://plnkr.co/edit/46O0znC5HFDE4cYXSm5h?p=preview

When storing data in cookies within the login function, follow this structure:

$cookies.userinfo = {
    'id': 1,
    'name': 'pqr'
};

To clear this data upon logout, simply use:

delete $cookies.userinfo;

Now, to check if 'userinfo' cookie is defined and redirect accordingly, do the following:

app.run(function ($cookies) {
      $rootScope.$on("$routeChangeStart", function () {
        if (angular.isDefined($cookies.userinfo)) {
            $location.path("/pathname");
        }
      });
});

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

Working with PHP to transfer toggle switch information to JSON

I'm currently experimenting with a combination of HTML, JavaScript, and PHP on a single page. My goal is to update a JSON file with either 0 or 1 based on the toggle switch state change. I seem to be close to achieving this functionality, but upon rel ...

Tips for creating a dynamic system to continuously add more HTML tables in PHP

I am working with an HTML table where the data is retrieved from a database. I need to add new rows to enter additional data, but the numbering does not continue from the last number. My question is how can I increase the numbering in the table. Please ref ...

Learning about extracting the route path variable in the node.js Express route.get() function

Why am I encountering a 404-NotFound error in this scenario? var test = require('./routes/test'); app.use('/test', test); router.get('/test', function (req, res, next) { //res.render('/test', { title: 'test ...

The Ng-include tag does not provide highlighting for its text

Within an ng-include template, I have a div that is not highlighting when hovered over. Although the cursor changes to a pointer when hovering over the text, attempting to click and drag to highlight it results in nothing happening. This issue is signific ...

Exploring the concepts of function referencing and prototypical inheritance in relation to function scopes

Consider the scenario where there are two distinct directives: angular.module('demo').directive('functional', [function (){ var idempotentMethods = ['idempotentMethod', 'otherIdempotentMethod']; return { res ...

Enhancing user engagement with PDF files using AngularJS to create an interactive and captivating page-turn

Anyone familiar with how to achieve a page turner effect for PDF files using Angular? I'm open to jQuery solutions as well. I've come across turn.js, which uses HTML, but I'm specifically looking for a way to implement this effect with PDF f ...

Select either one checkbox out of two available options

My form includes two checkboxes, allowing users to click on both of them. I'm wondering if it's possible to set it up so that only one checkbox can be selected at a time. For example, clicking on the first checkbox would turn it on while turning ...

Can I employ a PHP script as a "server" for a React application?

As I am using shared hosting without Node installed, I can't utilize Express as a server (or any other node-related features xD). The issue arises when fetching data from the Behance API in my app and encountering a CORS error. To address this probl ...

Executing vitest on compiled javascript files

Currently facing issues running vitest on compiled JavaScript. Numerous errors are appearing, such as: TypeError: Cannot read properties of undefined (reading 'spyOn') TypeError: Cannot read properties of undefined (reading 'mock') and ...

Error message: "User not found during passport authentication"

I am currently in the process of developing an authentication system for my website. However, I am encountering a specific error message when attempting to log in with any combination on the website: ReferenceError: user is not defined user is not define ...

Connecting a string array to the navigation bar

Need Assistance with AngularJS: In my controller, I have a string array that looks like this: var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About&apos ...

Tips for ensuring the directive stays current with changes to the parent scope variable

Example: <div ng-show="{{ display }}"> ... </div> angular.module('mymodule').directive('mydirective', [ function () { return { scope: { display: '=' }, ... }; ...

I am encountering difficulties with generating images on canvas within an Angular environment

I am trying to crop a part of a video that is being played after the user clicks on it. However, I am encountering the following error: ERROR DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may no ...

The Bootstrap 3.3 Carousel is stationary and does not rotate

I am facing a challenge with implementing a Carousel using Bootstrap version 3.3.7 on my website. The code snippet is as follows: <!-- Carousel ================================================== --> <div class="row dark-start d-none d-lg-block"&g ...

Do you think there is a more efficient way to solve this issue?

const [active, setActive] = React.useState(["active", "", "", "", ""]);``your unique text`` const hrefs = React.useMemo( () => ["/", "/about", "/skills", "/projects", "/contact"], [] ); React.useEffect(() => { setInterval(() => { ...

Accessing the locally stored data and displaying it in ng-bind

My journey to learn javascript through this project has hit a roadblock. I have stored an exchange rate in local storage: localStorage.gbpUSD = "1.42746"; Now, I want to utilize it instead of the hardcoded exchange rate in the code below... <input t ...

In my Flask Bootstrap website, the navigation bar remains unchanged by the presence of Javascript

I am currently in the process of creating a navigation bar for my Flask website using Bootstrap. However, when I implemented it into my HTML code, it is not displaying correctly which leads me to believe that the JavaScript may not be functioning properly. ...

Loading an animated SVG sprite file in real-time

Recently, I received an SVG sprite file from our designers to use in my app. The specified convention is to load the sprite at the top of the <body> element and then render icons using a specific code snippet: <svg class="u-icon-gear-dims"> ...

What is the process of resetting dropdown option values?

Recently, I have encountered an issue with a customized dropdown list in MVC4. I am populating data using AJAX and it is working fine, but the problem arises when the data is not cleared after successfully sending it to the controller. Here's an examp ...

Download the ultimate HTML package with a built-in chart.js component directly from your nuxt app

I have a task to create a compact Nuxt application that produces a basic HTML file containing informative sections about the services offered to the clients of my organization. The main purpose is to generate an HTML file that can be easily downloaded and ...