Double Tap Required to Update AngularJS Scope

Controller:

// Modal Controller
app.controller("ModalCtrl", ["$scope", "$filter", function($scope, $filter) {

  var date = new Date();
  var currentDate = $filter('date')(new Date(), 'MM/dd/yyyy');

  // Form Submit Actions
  $scope.submitFormCreateAccount = function() {
    $('#form-create-account').form('submit');
  };
  $scope.submitFormSignIn = function() {
    $('#form-sign-in').form('submit');
  };

  // Form Validation - Create Account
  $('#form-create-account').form({
      on: 'blur',
      fields: {
          email: {
              identifier: 'email',
              rules: [{
                  type: 'email',
                  prompt: 'Please enter a valid email address.'
              }]
          },
          displayName: {
              identifier: 'displayName',
              rules: [{
                  type: 'empty',
                  prompt: 'Please enter a display name for yourself.'
              }]
          },
          password: {
            identifier: 'password',
            rules: [{
              type: 'empty',
              prompt: 'Please enter a password'
            },{
              type: 'length[6]',
              prompt: 'Password needs to be atleast 6 characters long'
            }]
          },
          passwordConfirm: {
            identifier: 'passwordConfirm',
            rules: [{
              type: 'match[password]',
              prompt: 'Passwords don\'t match'
            }]
          }
      },
      onSuccess: function() {
        createUser();
        return false;
      },
      onFailure: function() {

        return false;
      }
  });
  // Form Validation - Sign In
  $('#form-sign-in').form({
      on: 'blur',
      fields: {
          email: {
              identifier: 'emailSignIn',
              rules: [{
                  type: 'email',
                  prompt: 'Please enter a valid email address.'
              }]
          },
          password: {
              identifier: 'passwordSignIn',
              rules: [{
                type   : 'empty',
                prompt : 'Please enter a password.'
              }]
          }
      },
      onSuccess: function() {
        signInUser();
        return false;
      },
      onFailure: function() {
        // Fail Function
        return false;
      }
  });

  // Create User
  function createUser() {
    email = $scope.createUserEmail;
    displayName = $scope.createUserDisplayName;
    password = $scope.createUserPassword;

    auth.createUserWithEmailAndPassword(email, password)
      .then(function(firebaseUser) {
        userId = firebaseUser.uid;

        // Add user to RealtimeDB
        database.ref('users/' + userId).set({
          name: displayName,
          email: email,
          added: currentDate
        });

        $('.ui.modal').modal("hide");
      }).catch(function(error) {
        console.log(error);
        $scope.modalErrorMessage = true;
        $scope.errorMessage = error;
      });
  };

  // Sign In User
  function signInUser() {
    email = $scope.signInUserEmail;
    password = $scope.signInUserPassword;

    auth.signInWithEmailAndPassword(email, password).then(function(value) {
      $('.ui.modal').modal("hide");
    })
    .catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;

      if (errorCode == 'auth/invalid-email') {
        console.log(errorMessage);
        $scope.modalErrorMessage = true;
        $scope.errorMessage = errorMessage;
      } else {
        console.log(errorMessage);
        $scope.modalErrorMessage = true;
        $scope.errorMessage = errorMessage;
      }
    });
  }

  // Sign Out User
  $scope.signOutUser = function() {
    auth.signOut().then(function() {

    }, function(error) {
      console.log(error);
    });
  }
}]);

View:

<div class="ui warning message modal-message"
         ng-show="modalErrorMessage">
      <div class="header">
        Whoops!
      </div>
      <p>{{errorMessage}}</p>
    </div>

Although all functions are working properly, there seems to be an issue where the error bits are not displayed until the createUser() or signInUser() functions are triggered twice. This occurs when these functions are invoked by a button click after validating the form. How can I ensure that the error messages are shown on the first click itself without having to run the mentioned functions twice?

Answer №1

To resolve the issue, I surrounded the $scope modifications with a setTimeout() method.

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

Can the Angular.js scope be maintained while also making changes to the template?

I am currently facing a challenge with my directive. In the snippet below, I am attempting to extract content from a template, append it to the layout, and then compile it: var $template = angular.element("<div></div>"); $template.append($co ...

Data not populating correctly in MEAN Stack application

Currently grappling with the challenge of making this web app operational using the MEAN Stack, I find myself at a standstill. The root cause is unclear to me. Upon refreshing my page and commencing data entry by filling out all fields before clicking on " ...

Having trouble calculating the number of days between two dates at this moment

I'm working with a code snippet that involves comparing two dates – a specified date and the current date. However, when trying to calculate the difference in days between these dates, I keep getting either 0 or an unexpectedly large number like "31 ...

Display a portion of the existing URL as a clickable link on the webpage using JavaScript or PHP

If I have a website with the URL and I would like to showcase the image at https://example.com/image.jpg on my site (), what can I do? I attempted the following approach, but it only displays the URL of the image. <p id="image"></p> <scri ...

Can the contents of a JSON file be uploaded using a file upload feature in Angular 6 and read without the need to communicate with an API?

Looking to upload a JSON file via file upload in Angular (using version 6) and read its contents directly within the app, without sending it to an API first. Have been searching for ways to achieve this without success, as most results are geared towards ...

Is it possible to override values set in the constructor(props) in React? If not, what is the best way to set defaults that can be overwritten later?

I'm confident I know the solution to this problem because my setState({}) seems to have no effect. This is the constructor code that I currently have: constructor(props) { super(props); this.state = { percentiles: { incN ...

What is the best way to utilize jspdf for formatting data, specifically when wanting the first column to be in bold?

How can I customize data formatting using jspdf? Specifically, I would like the first column to be in bold and the second column in normal text. Additionally, I want to align them in the middle of the pdf output with different colors for each column. Belo ...

React-redux: Data of the user is not being stored in redux post-login

Hello everyone, I am fairly new to using react-redux and I'm currently facing an issue with storing user information in the redux store after a user logs in. I am utilizing a django backend for this purpose. When I console out the user in app.js, it ...

The initialization of the R Shiny HTML canvas does not occur until the page is resized

I am currently facing an issue while integrating an HTML page with a canvas into my shiny R application using includeHTML(). The packages I am using are shiny, shinydashboard, shinycssloaders, dplyr, and DT. Everything is working perfectly fine except for ...

Is the Okta SDK compatible with all identity providers?

I am looking to incorporate a wide range of Identity providers into my app, such as Auth0 SSO OIDC, Onelogin SSO OIDC, Google SSO OIDC, and others. Is it possible to use this solution to make that happen? https://github.com/okta/okta-auth-js ...

Using jest.fn() to simulate fetch calls in React

Can anyone explain why I have to include fetch mock logic within my test in order for it to function properly? Let's take a look at a simple example: Component that uses fetch inside useEffect and updates state after receiving a response: // Test.js ...

What is the method for including a placeholder with sequential numbering?

When I click on the "Add String" button, it clones the first table row with an input in the table and adds it to the table. I also need to add a +1 number in the placeholder of the copied element. How can I determine the last placeholder before copying and ...

What could be causing my AngularJS code to malfunction?

I am having trouble with this code that is supposed to retrieve data from my web API. Despite checking multiple times, it still doesn't seem to be working. Can someone please assist me in identifying any mistakes in the code? var MyApp = angular.modu ...

Issue with React-Native FlatList's scrolling functionality

Struggling with implementing a scrolling FlatList in React Native. Despite trying various solutions found on Stack Overflow, such as adjusting flex properties and wrapping elements in views, the list still refuses to scroll. Snippet of code (issue is with ...

Can a Jquery *compiler* be developed?

Upon encountering this informative question, the idea of creating a jQuery compiler crossed my mind. The concept was to design a tool that could translate jQuery code into raw JavaScript code for execution. In my imagination, the process of executing a bl ...

What is the most effective way to redirect users accessing from Android devices?

Attempting to send all Android users to a designated page. I attempted this method using php, but uncertain of its reliability. Need assurance that it will work for all possible Android devices. Thoughts on the safety of this approach? <?php $user_ag ...

Can JavaScript be used to modify the headers of an HTTP request?

Can JavaScript be used to modify or establish HTTP request headers? ...

The div within the button is failing to properly adjust to height settings

Check out this Fiddle I'm currently working on a social thumbs up button and I've encountered some challenges. In my button design, I have included a second div to accommodate the right side of it. However, despite trying to adjust its height us ...

Learn how to generate a dynamic pie chart in PHP that can adjust its sections based on the user's input, giving you a fully customizable data visualization tool

let userData = [ { label: "History", data: 90 }, { label: "Science", data: 85 }, { label: "Art", data: 95 }, ]; I have written this javascript code to represent the user's data, but I want it to be more flexible an ...

The array functions properly when handwritten, but fails to work when loaded from a text file

I have been developing a password recommendation script that aims to notify users when they are using a commonly used password. In order to achieve this, I decided to load the list of common passwords from an external text file. However, it seems that the ...