Ways to alter the div post user authentication

I'm in the process of developing a website with a single-page application setup. I'm utilizing Node.js for the backend and Angular for the frontend. The challenge I'm facing is displaying a specific div when a user is not logged in, and switching to another div once the user logs in. What would be the most effective approach to achieve this?

Based on my current understanding, I've been using the ng-if attribute on both divs to toggle their visibility based on whether the user is logged in or not. I have an Angular function named isloggedin() for verifying the session.

Therefore, I used

<div ng-if="!checkLoggedin()">
in one div, and
<div ng-if="checkLoggedin()">
in the other.

Initially, when the page loads without the user being logged in, the conditions work as expected. However, after logging in, the second div doesn't appear. Is my expectation incorrect, or is there a better way to handle this? I've checked the function's value, and it provides data in one condition and 0 in the other. Have I made a mistake somewhere?

Below is the conditional code snippet:


var checkLoggedin = function ($q, $timeout, $http, $location, $rootScope) {
    var deferred = $q.defer();

    $http({
        method: 'GET',
        url: "http://localhost:3000/loggedin"
    }).success(function (user) {
        if (user !== '0') {
            $rootScope.message = 'You are logged in.';
            $timeout(deferred.resolve, 0);
            deferred.resolve();
            $location.url('/home');

        } else {
            $rootScope.message = 'You need to log in.';
            $timeout(function () {
                deferred.reject();
            }, 0);
            deferred.reject();
            $location.url('/login');
        };
    });

Here is the form code:

<form action="/#/home" ng-submit="login(user)">
    <!-- Form fields omitted for brevity -->
</form><!-- /form -->
                                 

Answer №1

Upon my observation, it seems that the following blocks:

<div ng-if="!checkLoggedin()">

and

<div ng-if="checkLoggedin()">

are executed during DOM load (page load), preventing any chance for the model to update. A recommended approach is to utilize a scope variable within the if blocks like this:

<div ng-if="isLoggedIn"> ... <div ng-if="!isLoggedIn">

and then update the variable's value in the success handler of the service call, as shown below:

var checkLoggedin = function ($q, $timeout, $http, $location, $rootScope) {
var deferred = $q.defer();

$http({
    method: 'GET',
    url: "http://localhost:3000/loggedin"
}).success(function (user) {
    if (user !== '0') {
        // set value here
        $rootScope.isLoggedIn = true;

        $rootScope.message = 'You are logged in.';
        $timeout(deferred.resolve, 0);
        deferred.resolve();
        $location.url('/home');

    } else {
        $rootScope.message = 'You need to log in.';
        $timeout(function () {
            deferred.reject();
        }, 0);
        deferred.reject();
        $location.url('/login');
    };
});

By implementing this method, we can ensure that the model reflects updated values and the correct if block will be added to the DOM.

Answer №2

It seems like your approach is on the right track, however there may be an issue with how you have defined checkLoggedin(), or perhaps it was used incorrectly.
There is another way to tackle this as well,
You can implement a different approach by applying a ng-if condition on the ng-model variable.

<label> User Name </label>
<input ng-model="username" />

For instance, you can add a condition based on the username value, such as:-

<div ng-if="username !== 'null' || username !== 'undefined'"> Display message if username field is touched </div>

<div ng-if="username === 'null' || username === 'undefined'"> Display message if username field is not touched </div>

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

AngularJS is incapable of detaching forms from objects

Creating forms dynamically using ng-repeat and adding them to the vm.forms object is causing issues. When an item is removed from the array, the corresponding form is deleted but the key in the vm.forms object remains, leading to undefined errors. angul ...

The button's URL will vary depending on the condition

As a newcomer to coding, I am seeking guidance on creating a button with dynamic URLs based on user input. For instance, let's say the button is labeled "Book Now" and offers two package options: Standard and Premium. I envision that if a user selec ...

JavaScript: Append an ellipsis to strings longer than 50 characters

Can the ternary operator be utilized to append '...' if a string surpasses 50 characters? I attempted this approach, however it did not work as expected. {post.title.substring(0, 50) + post.title.length > 50 ? '...&ap ...

What steps should I take to fix an error in my code?

My current objective is to write a program that generates a square with dimensions of 200 pixels by 200 pixels. The square should be colored using specific RGB values: red (red value of 255), green (green value of 255), blue (blue value of 255), and magent ...

React, Redux, Thunk - the trifecta of powerful

After spending a considerable amount of time struggling with this particular piece of code, I have scoured online resources such as Stack Overflow and the documentation, but there is still something that eludes me... The code in question revolves around t ...

Can you explain the distinction between these two Redux reducer scenarios?

While looking at someone else's code for a reducer, I noticed this snippet: export default function reducer(state, action) { switch(action.type) { case 'ADD_TODO': Object.assign({}, state, { ...

Transforming the appearance of the menu element in Vue using transitions

In my Vue app, I have this SCSS code that I'm using to create a smooth transition effect from the left for a menu when the isVisible property is set to true. However, I am encountering an issue where the transition defined does not apply and the menu ...

What is the process for resolving arguments in UI-Router's resolve function?

There seems to be a gap in my understanding of UI-Router and angular's documentation, so forgive me if this seems naive, but here goes: On http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$stateProvider, there is an example resolve fu ...

The Access-Control-Allow-Origin error is preventing the Angularjs post request from going through

I am encountering an issue with my index.html file that is sending a post request to localhost:3000/SetUser. The error I keep receiving states XMLHttpRequest cannot load https://localhost:3000/SetUser. No 'Access-Control-Allow-Origin' header is p ...

The ng-model is not properly syncing values bidirectionally within a modal window

I am dealing with some html <body ng-controller="AppCtrl"> <ion-side-menus> <ion-side-menu-content> <ion-nav-bar class="nav-title-slide-ios7 bar-positive"> <ion-nav-back-button class="button-icon ion-arrow-le ...

The node sends a request to the API to retrieve data, which is then stored in an array. Subsequently, another request is

var UfcAPI = require('ufc-api'); var ufc = new UfcAPI({ version: '3' }); const fighterIdList = []; function fetchFighterIds() { ufc.fighters(function(err, res) { for (let i = 0; i < res.body.length; i++) { ...

What strategies can be utilized to manage a sizable data set?

I'm currently tasked with downloading a large dataset from my company's database and analyzing it in Excel. To streamline this process, I am looking to automate it using ExcelOnline. I found a helpful guide at this link provided by Microsoft Powe ...

Unable to modify a variable within a request

Having trouble updating a variable within a request? It seems like the variable doesn't change when it should. const request = require("request"); var all = JSON.parse(body); var steamplayer = all['response']['players']['play ...

How to Stop AJAX Requests Mid-Flight with JQuery's .ajax?

Similar Question: Stopping Ajax Requests in JavaScript with jQuery Below is the straightforward piece of code that I am currently using: $("#friend_search").keyup(function() { if($(this).val().length > 0) { obtainFriendlist($(this).va ...

Instructions on integrating a column of buttons into a Bootstrap table containing information retrieved from a MySQL database

My bootstrap table is currently displaying data that is loaded from a MySQL database. I am looking to enhance it by adding a column with buttons, similar to the layout shown in this image. https://i.stack.imgur.com/8fWfR.png However, I am facing some dif ...

An error occurred stating "No matching closing tag found for "<%" when attempting to include the file

While attempting to include other .ejs files using the same syntax, everything works perfectly except when including my _show.ejs file. I am unsure where the issue lies, whether it is in the index.ejs or _show.ejs file. This is my index.ejs File <!-- i ...

Exploring the possibilities of integrating Keycloak with the powerful nuxt-auth

I am incorporating this particular authentication module in conjunction with Keycloak. In my nuxt.config.js configuration: keycloak: { _scheme: 'oauth2', client_id: 'client-bo', userinfo_endpoint: 'SERVER/protocol/open ...

What is the best way to display only li elements that possess a specific class utilizing javascript / jquery?

I have a bunch of li's: <ul> <li class="one"></li> <li class="one"></li> <li class="two"></li> </ul> and I want to display only the ones with the class "one" I attempted something like thi ...

Trigger the function upon successful completion of Stripe Checkout

I have a requirement in my Nodejs/Express API to execute a series of confirmation code once the checkout process is successfully completed in Stripe by the client. Below is the checkout function responsible for handling the checkout phase: // Checkout con ...

Stop the webpage from scrolling when clicking on a ui-grid field

Is there a way to prevent page scrolling when clicking on a row field in ui-grid? I'm working with a page that has ui-grid, and each row includes an anchor tag with a URL value linked and target="_blank" to open in a new tab like the example below: ...