Angular does not have the capability to automatically update itself

I have developed an angular project that includes a navigation bar. I would like the navigation bar to automatically update when users log in. I tried using ng-show and ng-hide to control it, but unfortunately, it doesn't seem to work. Can someone help me with this issue? I'm not sure if I have written the code incorrectly. I hope my question is clear, as English is not my first language.

<nav class="navbar navbar-default" role="navigation" ng-controller="UserCtrl">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" 
               data-target="#example-navbar-collapse">
                <span class="sr-only">Toggle Navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" ui-sref="index">Wishing Wall{{username}}</a>
        </div>
        <div class="collapse navbar-collapse" id="example-navbar-collapse">
            <ul class="nav navbar-nav">
                <li class="active"><a ui-sref="index">Home</a></li>
                <li ng-hide="isLogined"><a ui-sref="user.login">Login</a></li>
                <li ng-show="isLogined"><a ui-sref="user.info">Profile</a></li>
                <li ng-show="isLogined"><a ui-sref="user.wish">My Wishes</a></li>
                <li ng-show="sex == 'female'"><a ui-sref="user.putwish">Make a Wish</a></li>
                <li ng-show="isLogined"><a ng-click='doLogout()'>Logout</a></li>
            </ul>
        </div>
</nav>

<div class="container-fluid" ui-view>

</div>

Here is my controller's code:

app.controller('UserCtrl', ['$scope', '$state', 'LogoutService', function($scope, $state, LogoutService) {
if(sessionStorage.getItem('username')) {
    $scope.isLogined = true;
    $scope.username = sessionStorage.getItem('username');
    if(sessionStorage.getItem('sex') == 'male') {
        $scope.sex = 'male';
    } else {
        $scope.sex = 'female';
    }
} else {
    $scope.isLogined = false;
}

$scope.doLogout = function() {
    LogoutService.doLogout();
    sessionStorage.removeItem('username');
    sessionStorage.removeItem('sex');
    $state.go('index');
};
}]);
app.controller('LoginCtrl', ['$scope', '$state', 'LoginService', function($scope, $state, LoginService) {
$scope.doLogin = function() {
    var data = {
        username: $scope.username,
        password: $scope.password
    };
    LoginService.doLogin(data)
        .success(function(data, status){
            if(status === 200) {
                sessionStorage.setItem('username', data.user.username);
                sessionStorage.setItem('sex', data.user.sex);
                $state.go('index');
            }
        });
};
}]);

Answer №1

Take a look at this thread: How can I monitor state changes in $stateProvider in AngularJS?

To monitor route changes, set up a route change event handler that calls a function in the UserCtrl controller to verify the current login status.

Here's how you can structure your code:

app.controller('UserCtrl', ['$scope', '$state', '$rootScope', 'LogoutService',
    function($scope, $state, $rootScope, LogoutService) {
        var updateLoginState = function() {
            if (sessionStorage.getItem('username')) {
                $scope.isLoggedIn = true;
                $scope.username = sessionStorage.getItem('username');
                if (sessionStorage.getItem('sex') === 'male') {
                    $scope.sex = 'male';
                } else {
                    $scope.sex = 'female';
                }
            } else {
                $scope.isLoggedIn = false;
            }
        };
        $scope.logout = function() {
            LogoutService.doLogout();
            sessionStorage.removeItem('username');
            sessionStorage.removeItem('sex');
            $state.go('index');
        };
        // Check the login state upon controller initialization
        updateLoginState();
        // Monitor route changes and update login state accordingly
        $rootScope.$on('$stateChangeStart', function() {
            updateLoginState();
        })
    }
]);

Answer №2

To make things simpler, consider converting your isLogined variable into a function:

$scope.isLogined = function() { return sessionStorage.getItem('username') !== null; }

After that, update your view with the following code:

<li ng-hide="isLogined()">

Then proceed to implement a similar test for the situation

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

Adjusting the scope value following the completion of an HTTP request in AngularJS

I have a controller where I am making an ajax call to fetch some data. After the successful callback, I assign values to $scope variable as shown below. $http.get(GlobalService.getDomainUrl() +'/hosts/attr').success(function(data){ //Afte ...

Improperly styled select options - Fix it with JQuery

My issue is that my second select dropdown is showing each letter of the data retrieved from the server instead of displaying each item individually. Below is the JQuery code I am using: var selected_table = $("#id_TableName option:selected").text(); ...

transferring data to Amazon Web Services using Angular framework

I'm currently facing an issue while trying to send a file to an AWS server using an Angular dropzone. I have my AWS credentials ready, but I am unsure of how to properly make the request. Every time I attempt to drop the file into the dropzone, I kee ...

Encountering difficulties loading .mtl and .obj files using react-three-renderer

I'm currently utilizing react-three-renderer to load .obj and .mtl files, but I'm encountering difficulties in rendering the model. Instead, a cube is being rendered inside the div. My goal is to replace the cube with my desired .obj model. Inst ...

Issue encountered while configuring 'innerHTML' in xmlHttp.onreadystatechange function

Trying to create a JavaScript function that changes the innerHTML of a paragraph within an xmlHttp.onreadystatechange function, I encountered an error in the Chrome Console: Uncaught TypeError: Cannot set property 'innerHTML' of null at XMLH ...

The CE button on the calculator seems to be malfunctioning

My calculator's CE button isn't working as expected – instead of deleting the last entered number, it clears all numbers. I want the CE button to only delete the last number entered. Additionally, I want the calculator to display a default valu ...

Extracting server error messages on the client side using Node.js

Before storing data in the database, my server performs validation checks. If it is unable to save the data into the database, an error message is sent. In my client-side application, how can I retrieve and display this error message? Below is the HTTP r ...

Tips on deleting the lines following Texture Mapping

Why are there unwanted lines appearing on the sun sphere after applying texture mapping? I'm confused as to why these lines are showing up now. When we applied texture mapping in class, we didn't see these lines. Below is the code for the sun o ...

Find the initial occurrence of this element using AngularJS

Here's my query: In angular, how can I scan through JSON to locate the first occurrence of isPrimary:true and trigger a function with the corresponding GUID? I have a webservice that provides JSON data for available Accounts including display names a ...

I am facing an issue with resolving services in my AngularJS controller

Having trouble resolving the service data in AngularJS controller. var kattaApp = angular.module('kattaApp', []).controller('kattaController', function($scope, dataFactory) { var promise = dataFactory.getResult().then(function(data ...

Is there an "AlphaNumeric" choice available for the AdonisJS 5 Validator?

Hello everyone, I just finished reading the documentation for Adonis JS and I couldn't find an option to validate an "alphanumeric" value. In AdonisJS 4.1, this option existed, but now that I'm trying to migrate to Adonis 5, I can't seem to ...

What specific occurrences or processes initiate an HTTP POST request?

When considering the code snippet from an express app: var express = require('express'); var router = express.Router(); var standupCtrl = require('../controllers/standup.server.controller'); /* GET home page. */ router.get('/&a ...

Determining the total number of combinations possible from a collection of five arrays containing items

I have five massive collections filled with various strings, and each of them contains a different number of elements. Below are examples of the lists: List 1 "Jeffrey the Great", "Bean-man", "Joe", "Charles", "Flamur", "Leka", ...

Video in AngularUI Bootstrap Modal blinks during loading

I'm working on integrating an AngularUI based Bootstrap Modal window that includes embedded YouTube videos in iframes. The issue I'm encountering is that the modal window flickers at least once before fully loading the content. After researching ...

Is it possible that adding html tables together could result in the numbers being concatenated instead of summed?

When attempting to calculate the total sum of values in an html table column, my variable seems to be returning concatenated strings instead of the actual sum. For example, instead of 1 + 2 + 3 = 6, I am getting 1 + 2 + 3 = 123. The values in the "votes" ...

What is the process for placing a breakpoint within a "require"-d library using node inspector?

As I navigate through a library that is multiple layers deep from my project, I am facing the challenge of setting a breakpoint inside it. Node-inspector is a new tool for me, and I am currently exploring how to access the library and set breakpoints in i ...

"Encountered a problem while setting up the Mailgun webhook to handle both multipart and URL encoded

I have been working on creating a web hook listener for Mailgun, and I encountered an issue when I realized that Mailgun can post webhooks using either multipart or x-www-form-urlencoded content-types. Currently, my code uses Multer to handle multipart b ...

Tips for concealing an element with Clippy.js without relying on a timeout feature

Recently, I stumbled upon a fascinating JavaScript library called Clippy.js that allows you to incorporate Microsoft Word's classic virtual assistants into your web browser. While experimenting with it, I discovered that the text balloon vanishes afte ...

When using Vue3 along with Axios.post, the data is being serialized incorrectly

Goal: I need to send the data {"username": myuser, "password": mypswd} to an API endpoint in order to receive a token for further communication with the API. The following code snippets attempt to achieve this: // Attempt # 1 let re ...

Inquiry into the use of Jquery.ajax()

Hey there, I'm curious about using Jquery Ajax to retrieve a numeric value from a website. Any suggestions on where I should begin? Any advice would be greatly appreciated. Thanks in advance! Best regards, SWIFT ...