AngularJS redirection not fully functional

Having trouble with redirect in angularJS?

For instance, everything works smoothly when a user logs in. If the user is logged in (information stored in local storage), they are automatically redirected to '/dashboard'.

However, when the user logs out, instead of being redirected elsewhere as intended, it goes to 'http://localhost/ngJS/index.php#'. What am I doing wrong?

The ngJS folder serves as the project root, and index.php contains libraries and code inclusions. The websites are running on a local server called XAMPP.

MainAppMdl.js

var app = angular.module('mainApp', ['ngRoute']);
/*
 * Configuration for redirection
 * @param {type} $routeProvider
 */
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
     //WORKING
     .when('/', {resolve: {
                    "check": function ($location) {
                        if (localStorage.getItem('usr') && 
                                localStorage.getItem('usr') !== '0') {
                            $location.path('/dashboard');
                        }
                    }
                },templateUrl: 'pages/cover.html'
            })
    //WORKING LOADING THE CONTROLLER SUCCESSFULLY
    .when('/dashboard', {
                resolve: {
                    "check": function ($location) {
                        if (localStorage.getItem('usr') === '0') {
                            $location.path('/');
                        }}},
                templateUrl: 'pages/dummy.html',
                controller: 'logoutCtrl'
            })
    .when('/login', {
                templateUrl: 'pages/login/login.html',
                controller: 'loginCtrl'
            })
    .when('/logout', {redirectTo: '/'})
    .otherwise({redirectTo: '/'});
 }]);

LogoutCtrl

app.controller('logoutCtrl', function ($scope, $rootScope, $location, $log) 
{

        $log.log('logoutCtrl');
        $log.log($scope);
        $scope.message = $rootScope.message;

        $scope.logout = function () {
            if (typeof (localStorage) !== 'undefined') {
                localStorage.setItem('usr', 0);
                // NOT WORKING --------------------- redirect
                $location.path('/');
                // WORKING AND PRINTING ---------------------
                console.log('redirecting!');

            }
            /* No localstorage support */
            else {
                alert("Sorry. Localstorage is not supported");
            }
        };

    });

Logout-template.php

<section class="bg-success text-info" id="horizontal-nav-pills" >
                <nav>
                    <ul class="nav nav-pills nav-justified">
                        <li role="presentation" class="active"><a href="#">Home</a></li>
                        <li role="presentation"><a href="#/new-report"><span class="glyphicon glyphicon-plus"></span> Report</a></li>
                        <li role="presentation"><a href="#"><span class="glyphicon glyphicon-chevron-left"></span></a></li>
                        <li role="presentation"><a href="#"><span class="glyphicon glyphicon-chevron-right"></span></a></li>
                        <li role="presentation" ><a href="#" ng-click="logout();">Logout</a></li>
                    </ul>                           
                </nav>
            </section> 
            <!--end horizontal-nav-pills-->
 

Answer №1

Try this approach instead:

<a href="#" ng-click="logout();">Logout</a>

Consider using the following code snippet:

<a href="javascript:void(0);" ng-click="logout();">Logout</a>

Answer №2

  $scope.logout = function () {
        if (typeof (localStorage) !== 'undefined') {
            localStorage.setItem('usr', 0);
            // NOT WORKING --------------------- redirect
            $location.path('/');
            // WORKING AND PRINTING ---------------------
            console.log('redirecting!');

        }
        /* No localstorage support */
        else {
            alert("Tut uns leid. Localstorage wird nicht unterstützt");
        }
    };

The issue lies with:

$location.path('/');

It should have been corrected to:

$location.path('/logout');

Answer №3

It seems like the issue you are facing does not directly involve the codes for `ngJS` or `index.php` that you shared. Perhaps, the problem lies within a different file that is currently outside of your focus.

I recommend using an editor that has the capability to search through multiple files (such as Atom) and conducting a thorough search in the project directory for the terms mentioned above.

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

Locking mat-toolbar and mat-tabs to the top in Angular Material 2

As I work on my website, my goal is to fix the < Mat-Toolbar > at the top of the screen and then directly underneath that, lock the < Mat-Tabs >. The challenge I'm facing is that the position: fixed in CSS is not working as expected. When ...

Wheel of fortune - The chosen option does not align with the indicator

I am looking to create a game similar to a "Spinning Wheel" where users can select three possible outcomes and then spin the wheel. If any of the chosen three options appears when the wheel stops, the user wins. In the demo provided below, you may notice ...

Ways to determine the total amount of days in a given month

As I create a countdown timer, the process involves determining the remaining days in a given month by subtracting the current date from the total number of days in that month. For instance, if there are 30 days in September and 8 days have already passe ...

AngularJS combined with MVC is causing an issue where the table fails to refresh following an HTTP post request

When working with an $http.post() call and trying to update an HTML table in the success() callback, I encountered an issue: .success(function (data) { $scope.categories.push(data); }); Here is the HTML code for the table: <tbody> ...

Tips for executing flushall just once across various clusters with Node.js and Redis

Whenever my server starts up, I find myself needing to clear out the Redis memory. However, each time a new cluster is formed, it triggers a flushall command that wipes out everything in memory. Is there a way to only run flushall once on the very first se ...

Leveraging parameters within a sequence of object properties

Within the realm of Angular, I am dealing with interfaces that take on a structure similar to this (please note that this code is not my own): export interface Vehicles { id: number; cars: Car; trucks: Truck; } Export interface Car { make: ...

Difficulty with collapsing and expanding levels in Bootstrap 4 sidebar navigation

Having some trouble with my vertical Nav created using bootstrap 4. I have 2 levels of lists, but when I click on one dropdown, the other dropdown doesn't close. Here is a link to the issue: https://jsfiddle.net/thilanka/cr0Lfmd1 <ul class="na ...

The useCallback function is not producing the desired outcome in my code

Upon reviewing the code, it is expected that the useCallback hook triggers the display of the message 'rerendering has happened!' only when typing in the input field, and not when clicking on the Toggle button. However, the message does appear fo ...

Feed JSON data into a jQuery function using JavaScript

A rudimentary Google Apps Script Web App has been created with the sole purpose of displaying JSON data in an HTML drop-down list. The JSON file is stored in Google Drive. Code inspiration taken from: http://jsfiddle.net/manoj_admlab/Mta5b/3/ However, we ...

Issue with Parsley validation not functioning as expected

I have implemented parsley.js to validate my form, but I am facing an issue when trying to validate a checkbox using the data-mincheck attribute. Below is the snippet of my code: <form data-validate="parsley"> <p>Please choose at least 2 ...

Choosing a single item from multiple elements in React using React and typescript

In this particular project, React, TypeScript, and ant design have been utilized. Within a specific section of the project, only one box out of three options should be selected. Despite implementing useState and toggle functionalities, all boxes end up bei ...

Obtain the HTTP cookie from the browser

I am using AngularJS and I need to find a way to prevent the default cookie sent from the server, which has an expiration set to session. Alternatively, I would like to extract the authentication value from this cookie and save it to my own custom cookie f ...

Checklist options controlled by dropdown menus

I am facing a challenge with a collection of checkboxes that represent settings for equipment displayed on a page. The checkboxes are populated using ObjectdataSource and an IEnumerable method to bring distinct settings. Additionally, I have created a drop ...

Enable users to provide ratings ranging from 0.5 up to 5

I recently created a rating component that allows users to rate on a scale from 0 to 4.5, with increments of 0.5, which is causing unexpected behavior. I actually want users to be able to rate from 0.5 to 5 instead. How can I achieve this adjustment? Below ...

Looking to activate ng-switch based on the URL or browsing location

Is it possible to use a URL to directly access a specific tab element on a page? For instance, a URL such as: localhost:9000/widget&view=map would open the page with the map tab selected and display the content of the map tab. <div class="search-re ...

Is there a way to divide a string and insert something into the new array that is created?

I am facing an issue with adding a new fruit to a string that is converted into an array. Here's the scenario: var fruits = "banana,apple"; In an attempt to add a new fruit to this list, I tried converting it to an array and then using the push meth ...

Tips for confirming that one of three checkboxes has been selected in AngularJS

Here is the code snippet for checkboxes: <input name="chkbx1" type="checkbox" ng-model="LoanReferData.Prop1" ng-class="Submitted?'ng-dirty':''" required>Prop 1</input> <input name="chkbx2" type="checkbox" ng ...

Transferring information from the initiator to a pop-up window in Internet Explorer

I am looking to pass the scope and other values to a child window. It currently works as expected in Chrome, but not in Internet Explorer. Is there a workaround for this issue? var templateUrl = "/someviewpage"; var wOptions$ = 'menubar= ...

What is the best method for emulating ui-sref from an ng-swipe event?

State Change Triggered by Swipe: I am trying to change the state of my application using a swipe event. I have looked at the ui-router documentation which suggests using $state.go(), but I'm not sure if this is the best approach? QUESTION: How can I ...

Verify if the user is currently inputting text within a specific range of characters within

I am dealing with a specific issue involving a textarea. By default, this textarea contains a string of any type, but a user is only able to type inside opening and closing brackets. For example, "Leave[]" allows typing within the brackets but not outsid ...