The else statement is executed when an asynchronous call is made within an if statement

When an asynchronous call is made inside the if block, it raises the question of how the else statement block can be executed if doSubmit returns true. This often leads to reaching the line after the ERROR_2 comment:

$scope.save = function() {
    if (doSubmit) {
        var dto = {
            'attributes': $scope.fields,
            'requestOrigin': $location.absUrl()
        };
        var req = {
            method: 'POST',
            url: 'endpoint',
            data: dto
        };
        $http(req).success(function(data, status) {
            // SUCCESS
            $scope.completed(data);
        }).error(function(data, status) {
            // ERROR_1
            $scope.validationFailed();
        });

    } else {
        // ERROR_2
        $scope.validationFailed();
    }
}
// Function for displaying error messages related to validation failures
$scope.validationFailed = function(message, id) {
    $scope.alerts.push({ 
        type: 'danger', 
        msg: message || 'error.validation_failed', id: id || 'general'
    });
}

I recall reading about this specific scenario somewhere, but I cannot seem to remember the source. Any additional information or a brief explanation would be appreciated.

ADDITION 1: $scope.validationFailed

Answer №1

Here is my response:

What if the $http error callback is triggering the execution of $scope.validationFailed();? It might be worth experimenting by including alert(1); within your error callback.

This situation could potentially signify an issue on the server side, resulting in a status code other than 200. Both your else statement and the error callback appear to call the same function, but it highlights that the else statement is not being executed.

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 is the reason for ng-submit not being prevented by a mandatory select field?

In an HTML5 form, when a select element is required and no option is selected, the appropriate styling for invalidation is applied. However, the ng-submit still allows the form to be submitted. Why does this occur and is there a way to prevent submission ...

What does the main attribute in npm stand for?

The command npm init generates a file called package.json. The contents typically look like this: { "name": "webpack-tut", "version": "1.0.0", "description": "", "main": "index.js", .... } I came across this information in the official documen ...

Using jQuery to retrieve the TD value

I'm attempting to retrieve the TD value using the Value attribute.... Let's say I have the following HTML markup: <td nowrap="nowrap" value="FO2180TL" class="colPadding" id="salesOrderNumber1">bla bla </td> So, I tried this- v ...

Tips on incorporating `.env.local` into a script in `package.json`

Within my /src directory, I have several files named .env.*: .env .env.local .env.staging The content of src/.env is as follows: REACT_APP_NODE_ENV=123 The content of src/.env.local is: REACT_APP_NODE_ENV=456. To address this, I decided to install ...

Waiting for an Element to Become Visible in Selenium-Webdriver Using Javascript

When using selenium-webdriver (api docs here), how can you ensure that an element is visible before proceeding? Within a set of custom testing helpers, there are two functions provided. The first function successfully waits for an element to exist, howeve ...

Arranging elements in a list according to their position on the canvas using AngularJS

I am currently working on drawing rectangles on an html5 canvas using the JSON format provided below. My goal is to sort the array based on the x and y locations of each element. { "obj0": { "outerRects": [ { "outerRectRoi": { "x1": 0, " ...

Tips for iterating through PHP variables to perform multiplication in a for loop

I'm currently extracting data from a form and attempting to multiply them by values on the left-hand side increased in increments of 5. I have also included an image of the outcome. Sample Code: <?php if ($_SERVER["REQUEST_METHOD"] == & ...

Using node.js to set the billing address while confirming a Stripe Payment intent

Is there a way to specify the billing address of a payment intent with Node.js? When using the Stripe.js browser-side framework, I can easily accomplish this by utilizing Stripe elements and the stripe.confirmPayment function, which automatically captures ...

Checking if the file uploaded is in JSON format in Node JS: How to do it?

The Uploaded Code Within my node's app.coffee file, I have the following coffee-script code responsible for handling uploads: app.post "/import", (req, res) -> console.log req.files fs.readFile req.files.displayImage.path, (err, data) -> ...

Performing a jQuery ajax request by passing data obtained from iterating through elements

Is it possible to iterate through elements and send the element value within the data: {} parameter of $.ajax()? For example: $result = pg_query($connection, "select * from tbl_salary_deductions"); while($row = pg_fetch_assoc($result)) { ...

When deploying on Vercel, template literals cannot be used inside the src attribute of an image in NextJS

My issue involves displaying the client's picture after authentication using a userdropdown menu. The process of showing the user's image and name works smoothly with nextAuth when utilizing useSession(). https://i.sstatic.net/kBBa9.png Display ...

Tips for showing various column information as tooltips in ag grid's pivot mode

var ColumnDefinitions = [{ headerName: "Column A", field: 'colA', rowGroup: true }, { headerName: "Column B", field: 'colB', pivot: true, enablePivot: true }, { headerName: "Column C", field: ...

Exploring the power of Angular 1.5.6 with $postLink and typescript in web

I am struggling to implement $postLink in my directive using TypeScript and AngularJS 1.5.6. I'm unsure about the correct placement for this feature. Should it be a public function named "$postLink" within the directive's class definition? The a ...

What method can I use in pure Javascript to identify which day the week begins on, either Monday or Sunday, based on the

Can someone help me determine the start day of the week in local time using only Javascript? The start day could be Monday, Sunday, Saturday, or Friday. I came across this helpful resource on Stack Overflow: <firstDay day="mon" territories="001 AD AI ...

reaction to alteration in attribute

I have created a custom directive with an attribute: HTML: <my-directive id="test" myattr="50"></my-directive> JavaScript: myApp.directive('myDirective', function() { var link = function(scope, element, attrs) { scop ...

The issue with the $(window).width() property not functioning correctly in Internet Explorer

Currently, I have a Div element with absolute positioning: <div id="target" style="height: 300px; position: absolute; top: 275px;"></div> My goal is to calculate the horizontal resolution of the screen using JavaScript. With this width, I the ...

Utilizing AngularJS and $stateParams to showcase the details of an item on a dedicated page

Forgive me if this question has already been addressed elsewhere, but I'm struggling to grasp this concept after hours of trying. So here goes my post. I have a straightforward list of items from Parse.com that need to populate the list page. Each it ...

Manipulate an object in Three.js using the ObjLoader functionality

I'm currently working on manipulating an object loaded using OBJLoader in Three.js. The issue I'm facing is that while it's easy to manipulate the object once, I can't figure out how to do so during the animate loop or anywhere outside ...

A step-by-step guide to setting up a custom splash screen for React Native

Looking for assistance in setting up a splash screen in react-native specifically for Android devices. I've managed to successfully implement one for iOS, but I'm encountering difficulties when it comes to getting one to work on Android. I' ...

The AngularJS ng-if directive is failing to function properly, despite the logged boolean accurately reflecting the

I created a custom directive that handles the visibility of text elements on a webpage. While this logic works correctly half of the time, it fails the other half of the time. Here is the code snippet from my directive: newco.directive 'heroHeadline& ...