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

Discovering the name, id, and class attributes of a RadioButtonList within a content placeholder using JavaScript

Working on a web forms project with a Master Page implementation, I have added the following code in my content place holder. <asp:RadioButtonList ID="ckbLstPartner" runat="server" name="ckbLstPartner" RepeatDirecti ...

How can we incorporate Django template tags into our jQuery/JavaScript code?

Is it possible to incorporate Django's template tags within JavaScript code? For example, utilizing {% form.as_p %} in jQuery to dynamically inject forms onto the webpage. ...

Updating several inputs programmatically in VueJSLet's explore how to

I am working on a form that requires updating multiple other fields when one field is updated. For instance, I have a contact name field and depending on the name entered, I need to update the email and phone number fields as well. <template> < ...

AngularJs custom filter search option

Suppose I have an array of strings like ["don't worry", "worry", "Always be happy and don't worry" ] By default, when I search for the word "worry" using the ng-repeat search filter, it returns all three results regardless of the position of "wo ...

Ways to make a component gradually appear and disappear in an Angular application

I have developed a task management application using Angular and I wanted to implement a fading effect for each task when it is created and before it is deleted. Despite successfully applying the fade in effect at the todo-item component level, I encounter ...

Storing input field values in JavaScript using the onchange event handler.Would you like a different revision

I am looking to calculate the area by multiplying width and height entered into input fields, and then display the result. Any guidance would be greatly appreciated. Thank you! Here is my current code. const width = document.querySelector("#width"); con ...

Using UI-Router to create diverse layouts

I have a project where I require 2 different layouts. One is a simple 1 column layout (like a landing page), and the other is also a 1 column layout but with a menu at the top. I've created 2 HTML layouts that I'm using in my states, but the iss ...

Loading identical code in two different div elements

I am in the process of designing a comprehensive resource database featuring a side-scrolling container. Once a user clicks on a thumbnail within the container, the contents of a corresponding div will fade in and display specific category content. Each di ...

Is it possible to generate two output JSON Objects for a JavaScript line chart?

How can I display two lines in a Chart.js line chart using data from a JSON file with 2 objects stored in the database? When attempting to show both sets of data simultaneously, I encountered an issue where the output was always undefined. Why is this hap ...

I'm looking for a way to use AngularJS to automatically populate options in a second select list based on the value selected in the first select list

My current HTML and javascript code is used to fill a select box dynamically using AngularJS: <select data-ng-model="selectedTestAccount" data-ng-options="item.Id as item.Name for item in testAccounts"> <option value="">Select Account ...

Tips for troubleshooting the error message "Unable to access 'module' property of undefined" in AngularJS?

When I run the script test.bat in console, I encounter this error: Error: Uncaught TypeError - Cannot read property 'module' of undefined Chrome version 48.0.2564 (Windows 7) I am currently using Windows 7 and Angular Seed for my project. ...

Sharing CSS styles among multiple single-page applications (SPAs) developed using the React

I am currently working on multiple micro SPAs that exist independently within an Express environment. I am facing a challenge with importing a global CSS file that is located outside of the apps, as it is not being recognized. The use of @import url(asset ...

The Google Apps Script will activate only on weekdays between the hours of 10 AM and 5 PM, running every hour

function Purchase() { var ss=SpreadsheetApp.getActive(); var sheet=ss.getSheetByName("Buy"); var Cvalues=sheet.getRange(2,3,sheet.getLastRow()-1,1).getValues(); var Avalues=sheet.getRange(2,1,sheet.getLastRow()-1,1).getValues(); var r ...

The function was not invoked as expected and instead returned an error stating "this.method is not

I need help with an issue in my index.vue file. The problem lies in the fancy box under the after close where I am trying to call the messageAlert method, but it keeps returning this.messageAlert is not a function Can someone please assist me in resolving ...

Flickering of image in JavaScript when mouse is hovered over and removed

I recently encountered an issue while attempting to create a mouseover effect that would display a larger image when hovering over a smaller default image. The problem arose when the larger image started flickering uncontrollably upon hover. Check out the ...

"Using ng-click to access values from other elements in AngularJS

Can someone help me retrieve the value of an input field when a button is clicked? Here is my controller code: app.controller('MainCtrl', function($scope) { $scope.test = function(val) { alert(val); } }); This is my HTML snippet: < ...

Troubleshooting: ng-disabled feature is not properly functioning with Bootstrap buttons

I am currently using a combination of bootstrap.js and angular js in my project. The code snippet I have is as follows: //snippet from the controller $scope.isWaiting = true; $scope.promise = $http.get("voluumHandler.php?q=campaigns&filter=traffic-sou ...

Error 404 encountered when attempting to refresh a Single Page Application built with React Router on GitHub Pages

My website was created using React and React Router, hosted on Github Pages. Whenever I try to refresh a page that isn't the home page or open a new tab using ctrl+click, I encounter a 404 error. This is because Github Pages doesn't support front ...

Title: "Customizing Labels on Stack Bars and Lines in D3.js Visualization"

Currently working on a stacked bar chart with a line chart on dual axis using D3.js and facing difficulty aligning labels correctly. Check out the code I have experimented with so far: https://plnkr.co/edit/doobXBC5hgzvGwDLvArF?p=preview I am looking to ...

Ways to alert user prior to exiting page without initiating a redirect

I have a feature on my website where users can create and edit posts. I want to notify them before leaving the page in these sections. Here's how I can accomplish that: //Add warning only if user is on a New or Edit page if(window.location.href.index ...