The AngularJS alert success message does not display the success div immediately after the function returns a successful response

Here is the HTML code snippet for users to input their email address and student ID:

<div id="statusScope" class="pos-rel" style="margin:0 auto 50px;" ng-controller="statusController">
  <form class="form-inline text-center" action="">
    <div class="form-group">
      <label for="email">Email address:</label>
      <input type="email" class="form-control" id="email" ng-model="email">
    </div>
    <div class="form-group">
      <label for="sID">Student ID:</label>
      <input type="text" class="form-control" id="sID" ng-model="sID">
    </div>
  <br/>
  <br/>
    <button type="button" class="btn btn-primary" ng-click="emailCheck()">E-mail Check</button>
  </form>
  <div class="alert alert-success" ng-if="msg.success">{{msg.success}}</div>
  <div class="alert alert-danger" ng-if="msg.noStudent">{{msg.noStudent}}</div>
  <br>
</div>

The following code segment validates the entered email address and student ID, returning success if they match or "incorrect details" if they do not:

$scope.emailCheck = function() {
            var _to = $scope.email,
                    _studentID = $scope.sID,
                    _subject = "System Notify.",
                    
            var all = [].concat($scope.users.cis300, $scope.users.cis400, $scope.users.cis500);

            var student = all.filter(function(item) {
                return item.email == _to && item.studentid == _studentID;
            });

if(student && student.length) {
                    var _file1 = student[0].tfile;
                    var _file2 = student[0].tfile1;
                    var _file3 = student[0].tfile2;
                    _msg = "Hello, "+student[0].firstname+" "+student[0].middlename+". "+student[0].lastname+". \r\n"+"Your status is " + student[0].status + ". \r\n",
                    
                    $.post('php/mail.php', 
                    JSON.stringify({
                            'to': _to,
                            'subject': _subject,
                            'file1': _file1,
                            'file2': _file2,
                            'file3': _file3,
                            'msg': _msg

                    }),

                function(response, status) {    
                        $scope.msg.success = "Success! Check your Email";
                    });
                } else {
                    $scope.msg.noStudent = "Email or Student ID is incorrect.";
                }

While incorrect information triggers the "Student ID or Email is incorrect" message instantly, correct input results in an email sent to the user. However, the success alert only appears after making changes in the fields.

Answer №1

When a promise is resolved outside the digest cycle in Angular, any changes made to the `$scope` are not immediately visible. To ensure that Angular recognizes these changes and updates the view, you must wrap your modifications in `$scope.$apply()`. This will trigger a digest cycle and allow Angular to reflect the updates.

function(response, status) {
    console.log(_status);
    $scope.$apply(function() {
        $scope.isDisplay = true;
        $scope.msg.success = "Success! Check your Email";
    });
} else { [...]

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

Using MeanJS to assign a Mongoose object reference to an array in Angular

Having an issue with MeanJS and using the $update function of the $resource service in Angular provided by MeanJS. Here is a basic outline of my problem: Mongoose schema: var mongoose = require('mongoose'), Schema = mongoose.Schema; var Lotion ...

Is it possible to achieve Two-Way Binding in a custom directive without relying on NgModel?

I am creating a custom dropdown without using any input element or ngModel for two-way binding. Is it possible to achieve two-way binding with custom attributes? var mainApp = angular.module('mainApp', []); mainApp.directive('tableDropdo ...

Blending conditional and non-conditional styles in VueJS

Is it possible to set a class in Vue based on the value of a parameter and conditionally add another class if that parameter meets a certain condition? Can these two functionalities be combined into one class assignment? <button :class="'btn btn-p ...

What is the best way to ensure that each link displays unique text in a separate div when clicked on?

<aside class="side_article_content"><p id="defaultText">Chakras are explained here.</p> <p id="baseChakraInfo" style="display:none;">Base Chakra details here.</p> <p id="sacralChakraInfo" style="display:none;">Sa ...

The component in React does not refresh after updating the state

I have a React page where I am displaying a list of quizzes fetched from an external API. There's also a "New Quiz" button that opens a dialog with a form for users to create a new quiz. My issue is with making the table re-render once the POST reque ...

Condition formulation using dynamic dust JS equality

I'm struggling with a seemingly simple task - dynamically changing the @eq condition. The example provided shows a default render, but what I really need is to allow user input to change it to either "Larry" or "Moe". You can view my code on jsfiddle ...

Rendering the HTML5 canvas within a console environment

I am looking to create images of humans on the console using nodejs. In order to achieve images of higher quality, I require a library or module that can facilitate drawing images in the console. Some options available include imaging and console-png. How ...

Retrieve information from the API prior to rendering the controller components

Hello there! I am looking to retrieve data from a factory before any of my controllers are loaded. After some research, I discovered that it can be achieved using the resolve function in AngularJS: angular.module('agent', ['ngRoute',&a ...

What is the process for creating custom event bindings in AngularJS?

There is a custom event called core-transitionend (specifically triggered by Polymer), and I am able to specify an event handler using document.addEventListener(). However, what would be the most recommended approach for achieving this in AngularJS? Alter ...

reduce the size of the image as the browser width decreases

Struggling with a webpage layout that features an image on the left and content area on the right, both with fixed widths. When reducing browser width, the image should not shrink but be cropped from the left side instead. Any solutions for this issue? ...

Tips for saving 20000 table rows in the local storage of a Web Browser

I have been tasked with storing all records in the browser's local storage and utilizing them for searching, sorting data, and displaying results on the viewport. My preference is to use WebSql; however, not all browsers support it. I am seeking guida ...

The canvas is unable to render the image from the sprite sheet

I successfully drew an image representing the player, but now I'm encountering difficulties in drawing an enemy character. Despite adding alerts indicating that the program is executing the draw enemy function, the enemy character still doesn't a ...

Displaying React components for a brief duration of time

I have an existing React component where I need to display another component for a specific duration. Upon mounting or data loading of the parent component, the child component should become visible after 1-2 seconds and then disappear after a few more sec ...

populating a HTML image tag 'src' attribute with data extracted from API javascript code

Hey there! I'm currently working on integrating an image element from the openweatherAPI that corresponds to the weather icon retrieved from the JSON data when a user inputs a city. This means displaying images like scattered clouds or clear skies bas ...

Is it possible to ensure a div occupies all available space within a column using the vh-100 class in bootstrap?

In the <div class="bg-primary"></div> element, I'm trying to make it take up the remaining empty space without exceeding the vh-100. I've experimented with various solutions but haven't been able to find a fix yet. b ...

What is the best way to empty an array within the state of a React component using JSX?

I need assistance with a React and JSX project where I am creating input fields that can be removed by clicking a button. Currently, I have an empty array stored in the state of the Page component. This array is updated using the addItems function. Howev ...

Implementing GRIDFS for mp3 storage in a meteor application

Being a novice in the world of meteor, I am currently working on defining an mp3 collection and then uploading music to it from the admin page. The packages that are installed include: cfs:standard-packages cfs:gridfs cfs:filesystem 1) I have successful ...

Is it possible to dynamically display various templates for an Angular 1.5 component based on certain conditions?

I have multiple angular 1.5 components that share the same attributes and data structure. It seems like they could be consolidated into a single component, but I need a way to dynamically select a template based on the value of the type attribute. var myC ...

The behavior of input types disabled and readonly varies when combined with a hyperlink (a href

In the code snippet below, I am trying to disable and enable a calendar clickable icon. <p> <label> <input type="text" name="date18" id="date18" value="01/01/2012" style="width:75px;" disabled/> </label> ...

Upon loading the page, a forward slash is automatically added to the end of the URL

My website has multiple pages of content, but I've noticed a strange issue with the URLs. When I navigate to example.com/guides, a forward slash is automatically added to the address bar, resulting in example.com/guides/. Surprisingly, the page still ...