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

Troubleshooting a problem with AJAX returning the data

Currently, I have a javascript function that calls another javascript function called zConvertEmplidtoRowid. This second function utilizes an ajax call to execute a query and retrieve data stored in a variable named rowid. My challenge lies in figuring out ...

Incorporating object into main function of VueJS root component

I have integrated VueJS into my HTML template for an application. When a button is clicked, it passes the object of a component to its root in the following manner: <button v-on:click="$root.savePlan(dataObj)"></button> The dataObj is passe ...

Can someone provide guidance on how to send serialized data using a jQuery.getScript() request?

Is it feasible to make a request for an external JS file while simultaneously sending serialized data in that same request? I want to provide some values to validate the request, but without including those values in the request URL. Upon receiving the po ...

Utilizing PHP for Interactive JavaScript Modals

Encountering an issue with my JavaScript. The modal initially functions correctly, but upon clicking it for the second time, two modals appear - one from the previous click and another new one. The stacking of modals continues each time the button is cli ...

Top method for showcasing only unique values from various div tags with identical class names

Is there a way to show only unique values from multiple divs with the same class name? <div class="categories">cat 1</div> <div class="categories">cat 1</div> <div class="categories">cat 2</div> <div class="categorie ...

Transferring SQL server dates to jQuery Calendar through AJAX communication

I am currently working on implementing a jQuery calendar example, and I want to load the dates from my SQL database instead of using hardcoded values. I am considering using Ajax post to send a request to my web method and retrieve the data. However, I am ...

How to Retrieve Information from an Array in VueJS

At the moment, the data being displayed on my page is an array, as shown in the snippet below: https://i.stack.imgur.com/zAvrc.png However, I only want to retrieve or display the project names. This is all I have at the moment: fetch(context,id){ ...

Combining two items from separate arrays

How can I efficiently merge objects that share the same index in two different arrays of objects? Below is the first array const countries = [ { "name": "Sweden", "nativeName": "Sverige" }, ...

Creating a bot that will only respond once when a user sends multiple photos simultaneously

I'm currently working on a Telegram bot using nodejs. I am utilizing the node-telegram-bot-api library and have implemented the on('photo') method to handle when a user sends a photo to my bot. However, I am facing an issue where if a user ...

How can I prevent right-clicking with Ctrl+LeftMouseClick in Firefox on MacOS?

I'm looking to implement a shortcut using Ctrl+LeftMouseClick in my React project. It functions perfectly on Chrome on my Mac, but in Firefox the shortcut initiates a right mouse click (event.button = 2). I believe this may be due to MacOS's Rig ...

Saving extra parameters with MongooseJS

When saving data in my app using a POST query, how can I include additional parameters to the Item? For example, I would like to add user: req.user._id. var Item = new Model(req.body); Item.save(function (err, model) { res.send(model); }); ...

Definitions that are displayed dynamically when hovering over a particular element

I am seeking a way to implement popup definitions that appear when a div is hovered over. My website showcases detailed camera specifications, and I want users to see a brief definition when they hover over the megapixel class called '.mp'. One o ...

The Intersection of Angular JS and Web API Design

Currently working on designing an architecture that includes the following technologies: Angular JS 1.5 MVC 5.0/Web API. EF 6.0 Considering whether it is beneficial to have a single web project containing both Angular JS and Web API functionalities. We ...

Develop a Vue component for a fixed sidebar navigation

I am in need of a vertical navigation bar positioned to the left of my app's layout, with the content extending across the right side. However, I am currently facing an issue where the navbar is pushing all the content downwards. How can I resolve thi ...

Inject a dynamic URL parameter into an iframe without the need for server-side scripting

I'm really stuck and could use some assistance with the following issue, as I am unable to solve it on my own :( When a user is redirected to a form (provided via an iframe), there is a dynamic URL involved: website.com/form?id=123 The code resp ...

What is the best way to remove the excess numbers from the return date provided by the react-date-picker?

I need help displaying only the Month and Day with the format "Tue Oct 22 2019". Currently, I am getting "Tue Oct 22 2019 00:00:00 GMT-0700 (Mountain Standard Time)" when using "react-date-picker". How can I achieve this without having to truncate the te ...

Working with conditional statements in ReactJS and Javascript

As I navigate the circle object using arrow keys, I am facing a challenge in limiting its movement within the height and width of the svg area. Despite my efforts to use conditional statements, the ball tends to get trapped at the edges and fails to contin ...

How can I integrate an angular-formly template with a custom UI/CSS library?

Seeking advice on incorporating a custom Angular-formly template into my application. I prefer not to use the Bootstrap template as I have my own UI/css library. Should I opt for angular-formly-templates-vanilla or angular-formly-templates-bootstrap and mo ...

I keep running into an issue whenever I attempt to import material ui icons and core - a frustrating error message pops up stating that the module cannot be found

[I keep encountering this error message when attempting to utilize @material-ui/core and icons] `import React from "react"; import "./Sidebar.CSS"; import SearchIcon from "@material-ui/icons/Search"; const Sidebar = () => { return ( <> ...

Unable to assign a value to an indexed property in 'FileList': Setter function for index properties is not enabled

angular.module('myApp') .directive('fileModel', ['$parse', 'uploadService','messageService','CONF', function ($parse, uploadService,messageService,CONF) { return { restrict ...