Angular JS Visibility Toggling with Ng-Show and Ng-Hide

Working on an angular service for a login form, I've successfully implemented authentication using a factory with an http injector to handle HTTP credentials. However, I'm facing an issue in displaying an error message when incorrect credentials are entered.

To tackle this issue, I added a div with an ng-show directive set to the value of errorAlertTextElem. The goal is to display the error message element when the $resolved status of the resource factory is false. While this mechanism works momentarily, the error message disappears quickly after being displayed when entering wrong credentials and clicking 'sign in'. I've attempted to use $scope.$apply() but since the digest is already in progress, this approach doesn't solve the problem. What am I overlooking here?

Snippet of Angular Controller code:

//Angular.js controller snippet
loriaGameControllers.controller('signinController', ['$scope', 'Users', function($scope, Users) {
  
  $scope.signin = function() {

    // 'Users' factory makes a restful resource call
    var test = Users.userInfo().query(); //this returns a promise and $resolved

    console.log(test);

    if (test.$resolved == false) {
      $scope.errorAlertTextElem = true; //Attempt to set the ng-show value to true to display the error box when needed.
    }
  };

}]);

Signin Form Code within the HTML (Inside ng-app):

<form class="form-signin col-md-6" role="form" name="signinForm" ng-controller="signinController">
  <h2 class="form-signin-heading">Sign In</h2>

  <div class="alert alert-danger" ng-show="errorAlertTextElem">Invalid Username or Password</div>
  
  <input type="email" class="form-control" placeholder="Email address" ng-model="username" name="username" required autofocus>
  
  <input type="password" class="form-control" placeholder="Password" ng-model="password" name="password" required>
  
  <label class="checkbox">
    <input type="checkbox" value="remember-me"> Remember me
  </label>

  <div class="btn btn-lg btn-primary btn-block" ng-click="signin()">Sign in</div>
</form>

Answer №1

The problem has been successfully resolved. It was discovered that the injector I was using had been relocated, causing the template to reload each time the injector ran.

Answer №2

The angular resource only triggers rejection when an HTTP error occurs. This means that if a '404' or '505' error occurs, the resolve will be false. To ensure your code functions correctly, you need to handle the response from the server in order to display any relevant messages.

test.$promise.resolve(function(response){
     // Handle errors coming from the server 
     console.log(response);
     // Display error message?
});

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

What are the steps to redirect from a nested route back to the top route using Node.js with Express?

Is there a way to redirect from a nested route to a top route in Express.js? In the following code snippet, how can we make the callback for the route /toproute/nested redirect to /profile instead of /toproute/profile? // app.js const express = require(& ...

What is the best way to retrieve recently inserted data using Sequelize in PostgreSql?

Is there a way to retrieve updated table values after adding a user to the "WOD" table without making an additional query? Currently, when I add a third user to my WOD table, I can only return the first two users because I am unable to access the updated ...

Transmitting an email form using AJAX, Bootstrap, and Jquery

I am attempting to email a form using the code snippet below. This is a modified version of Bootstrap Validator created by 1000hz. $('#form').validator().on('submit', function (e) { if (e.isDefaultPrevented()) { alert("not workin ...

javascript accessing all data in firebase real-time database using JavaScript the right way

Working with node.js, I am retrieving data from the firebase real-time database. However, the data is being returned in the following format: Data Retrieval Code import firebaseApp from '../config.js'; import { getDatabase, ref, onValue } from & ...

How can I change a PHP for loop to Javascript?

Can the following code be converted to JavaScript? for (let lift of liftDetails) { document.write('<option>'+ lift["LiftMakes"] +'</option>'); } ...

Problem with HTML relative paths when linking script sources

Having trouble with a website I constructed using Angular. The problem lies in the references to javascript files in index.html. The issue is that the paths in the HTML are relative to the file, but the browser is searching for the files in the root direct ...

NodeJS hit with ECONNREFUSED error while trying to run localhost server

I currently have a NodeJS server running on my local machine, listening to port 50000. I am trying to make a simple GET request to this server from another local server, but I keep receiving an ECONNREFUSED error message: { Error: connect ECONNREFUSED 127 ...

The state in Reactjs is not displaying as expected

Check out my ReactJS todo app that I created. However, I am facing an issue with deleting todos. Currently, it always deletes the last todo item instead of the one I click on. For example, when trying to remove 'Buy socks', it actually deletes ...

Tips for managing image uploads while incorporating pre-set error detection into a form

I'm facing a challenge with integrating an optional image upload feature into my express app. The issue seems to be related to the way I've structured the app, as it appears to be trying to pass the image name from the body instead of utilizing t ...

How to Enhance Angular ui-router nested views with Resolve?

I have been working on creating a customized version of my Angular 1.4.12 application with nested views. The main purpose behind this customization is to accommodate sections within the app that require a header/content/footer structure, while others do no ...

Unable to retrieve data from the JSON object

I'm struggling to extract the data value from a JSON object. Let me share my code snippet: var ab_id = $( "#ab_id" ).val(); $.ajax({ type: 'GET', contentType: 'application/json', url: 'edit_account.php', ...

Troubleshooting: Mongoose Array Object Order Modification Issue

Imagine we have a person named Michael who lists his favoriteFruits as [ { name: 'Apple'}, {name: 'Banana'} ] The challenge at hand is to change the order of his favorite fruits. In other words, we want to transform it from: [ { name ...

When using Browserify, the function require() on a concatenated string will not include the module in the output script

When using require() to create a combined string path, the path of the module will not be included in the output script. Examples of this include: require("./"+"b" ); //or var path="./"; require(path+"b"); Let's say we have a.js module.exports="a"; ...

Tips for keeping a login session active on multiple tabs

As I am in the process of developing a website, one issue I am facing is determining the most effective method to maintain user login sessions. Currently, I am utilizing Html5 web storage known as "session storage" to keep track of whether a user is logged ...

Issue: The module '[object Object]' could not be located

const express = require('express'); const app = express(); const jade = require('jade'); const path = require('path'); const server = require('http').createServer(app); const io = require('socket.io').liste ...

JavaScript: Learn how to simultaneously open two links from the current webpage

I am trying to create a browser bookmark that will open a link with the id: window.getElementById('updateOk').click() followed by opening a small window with another button: document.getElementsByClassName('rmit-save-details btn btn-inlin ...

What is causing only one route to be functional with the Backbone Router?

In the segment below, I have incorporated a variety of routes and view events created using Backbone.js. All the routes seem to be working as expected except for the last one 'products'. Initially, I had it set up differently but noticed that it ...

Encountering an Uncaught TypeError that is hindering an alert for the score, but I am uncertain about the solution despite the game functioning properly

My Yahtzee code is functioning normally during gameplay, but I'm facing issues with getting alerts for the total score and bonus points. I have identified where the problem lies but I am unsure how to resolve it. I attempted debugging through alerts, ...

React callbacks involve the interaction between three different components

Currently, I am working with 3 distinct components: -The friendsPage component contains a list of friends and invitations to friends -The friendComponent displays detailed information about a friend along with possible actions (which are handled in the t ...

AngularJS - smooth scrolling with $anchorScroll duration

While going through the AngularJS documentation, I have not been able to determine whether $anchorScroll has a duration or easing option for smoother scrolling to elements. The documentation only shows: $location.hash('bottom'); // call $ancho ...