ng-model does not reflect changes after making an $http request

I attempted to modify the ng-model value after making an $http.get call, but it does not reflect the update.

Below is my code snippet:

main.js

angular.module('app', [])
  .controller('mainCtrl', ['$http', function($http) {
    var main = this;
    main.show = true;

    $http({
      method: 'GET',
      url: 'api url'    
    })
    .then(function(res) {
      main.show = true; 
      console.log('Successful call, main.show: ' + main.show);        
    }, function(res) {
      main.show = false;
      console.log('Failed call, main.show: ' + main.show);
    });

    console.log('Outside of call, main.show: ' + main.show);
  }]);

index.html

...
<body ng-app='app' ng-controller='mainCtrl as main'>
  <a ng-show='main.show' href='/'>Success</a>
  <a ng-hide='main.show' href='/'>Failure</a>
</body>
...

Console log when API call succeeds:

Outside of call, main.show: true
Successful call, main.show: true

Console log when API call fails:

Outside of call, main.show: true
Failed call, main.show: false

The issue I'm facing is that the HTML always displays the 'Success' link.

I have tried various methods like using $timeout, $apply, but none seem to work.

Although there are solutions available for similar issues, they haven't proven effective in my case.

How can I resolve this problem?

Answer №1

Everything is running smoothly.

Check out the example below. I purposely linked to the incorrect URL so the service request will fail, triggering the failure callback function.

Example

angular.module('app', [])
  .controller('mainCtrl', ['$http', function($http) {
    var main = this;
    main.show = true;

    $http({
        method: 'GET',
        url: 'http://jsonplaceholder.typicode.com/photos1'
      })
      .then(function(success) {
        main.show = true;
        console.log('Successful call, main.show: ' + main.show);
      }, function(error) {
        main.show = false;
        console.log('Failed call, main.show: ' + main.show);
      });

    console.log('Outside of call, main.show: ' + main.show);
  }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>

<body ng-app='app' ng-controller='mainCtrl as main'>
  <a ng-show='main.show' href='/'>Success</a>
  <a ng-hide='main.show' href='/'>Failure</a>
</body>

Answer №2

Your approach to handling HTTP calls is not quite right.

First, in the controller:

.controller('mainCtrl', ['$http', function($http) ...

In the controller, the first reference to $http should be enclosed in single quotes: '$http'.

Performing asynchronous calls can be done in the following manner:

var promise = $http({
            method : 'POST',
            url : baseUrl,
            headers : {
                'Content-Type' : 'application/x-www-form-urlencoded'
            },
            data : data
});

promise.then(function (response) {
        yourData = response.data;
        console.log(response.data);

        return yourData;
    })
    .catch(function (error) {
        console.log("Something went terribly wrong.");
    });

Answer №3

The console.log('out of call, main.show: ' + main.show); statement is printed before the completion of the http request in the given code snippet. As a result, main.show always holds the value true. To access main.show accurately, you need to wait until the http request either succeeds or fails.

var main = this;

main.show = true;

$http({
  method: 'GET',
  url: 'url'    
})
.then(function(res) {
  main.show = true; 
  console.log('succeed call, main.show: ' + main.show);        
}, function(res) {
  main.show = false;
  console.log('failed call, main.show: ' + main.show);
  DoSomething();

});
function DoSomething(){
    console.log('out of call, main.show: ' + main.show);
}

Answer №4

Assign a starting value of false to main.show

main.show = false;

Add the ng-app attribute to the HTML tag

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

Encountering a buffer error when utilizing child processes in Express

I'm currently working on a project where a user can upload a document and a Python script located on the server side in a MERN stack application will be executed using child processes to determine if it returns true or false. However, when I try to op ...

``Maintain user engagement with a dynamic menu by utilizing knockout for view switching and CSS

I'm facing a challenge with my single-page application developed using knockout/jquery. The issue lies in handling which view to display as the number of menu items increases, making the code more difficult to manage. I'm looking for a solution t ...

Issue: Unable to locate module - Error in integration of Vue.js with Laravel framework

I'm currently following a tutorial on YouTube for setting up Vue and Laravel. My resources folder structure looks like this so far: - resources - js - app.js - vue -app.vue In my app.js file: require('./bootstrap&ap ...

Enumerated type alias in Typescript

Within my typings file, I have the following: declare namespace Somatic { enum PropType { html, object, css } } In a separate file named index.ts, I create a shorter alias for this enum like so: type PropType = Somatic.Pr ...

Exploring the View-Model declaration in Knockout.js: Unveiling two distinct approaches

For my latest project, I am utilizing Knockout.js to create a dynamic client application with numerous knockout.js ViewModels. During development, I came across two distinct methods of creating these ViewModels. First method: function AppViewModel() { thi ...

Using JavaScript to Implement a Scrolling List

Currently, I am diving into the world of coding with HTML, JavaScript, and CSS for a college project. Unfortunately, my instructors aren't providing any assistance, so I'm turning to you for help. I have managed to put together some code to crea ...

In IE8, submitting an Ajax request almost always results in an error being

This piece of code seems to be causing some trouble, as it works fine in all browsers except for IE8 on an XP machine. No matter what I try, the error function keeps getting triggered specifically in IE8. I've experimented with different dataTypes lik ...

Inaccurate data is being shown by the Ajax method

I have a question that I haven't been able to find a satisfactory answer for: Recently, I started learning about AJAX methods and I'm trying to post some information processed by a php page named page.php. In my HTML file, I've included th ...

The payload is properly returned by the Reducer, however, the component is receiving it as

In my current project, I am developing an application that involves fetching data from a firebase database. This particular database does not require authentication, and I have already adjusted the access rules to allow for public access. One of the actio ...

Create a new array containing two objects that have values taken from two separate objects with the same key in Javascript

I've been attempting to achieve something I've been wanting to do: I have two objects with the same keyName but different values. I need to create a new array that contains a new object with two entries, each holding the values from the two obje ...

Passing data to a server-side component in Next.js: a guide

I am working on a website dedicated to dynamic blogs and I need to pass parameters to an API URL in order to retrieve a specific blog. However, I must ensure that the approach I take does not hinder SEO by utilizing local storage, cookies, or any other c ...

Managing Dark Mode in Material UI with Redux

Having a React application integrated with Material UI, I encountered an issue with the dark mode functionality. Whenever I attempt to modify the dark mode state on a page where the content is rendered from redux state data, the entire page crashes. It app ...

In JavaScript, constructors do not have access to variables

Currently, I am attempting to implement Twilio Access Token on Firebase Functions using TypeScript. export const generateTwilioToken = functions.https.onRequest((req, res) => { const twilioAccessToken = twilio.jwt.AccessToken; const envConfig = fun ...

Receiving blank information from Firebase

I am struggling with retrieving data from my Firebase tree and converting it into a JSON object. https://i.sstatic.net/YmxRh.png Despite trying the code below, I'm only getting an empty result on my browser: const http = require('http&apos ...

What methods can I use to ensure accurate validation of dates?

I have encountered an issue with using celebrate to validate dates. Despite this, I am still able to add a start_date that is higher than the end_date. How can I prevent this behavior? Additionally, when I try to use the format 'YYYY-MM-DD', I re ...

What is the method for retrieving information from a JSON file that has been uploaded?

I am working with some HTML code that looks like this: <input type="file" id="up" /> <input type="submit" id="btn" /> Additionally, I have a JSON file structured as follows: { "name": "Jo ...

What is the process for updating the values of all objects within an array of objects using Javascript?

I am attempting to update the values of car in all objects within an array called data with the values from newData. Here is my code snippet: import "./styles.css"; const data = [ { id: 1, car: "Toyota 2020", owner: "BM" }, ...

Sending auth0 token as a parameter in $http.get request in Angular

I am encountering difficulties when trying to attach the auth0 token to a http.get request for an API that requires the token. The token is generated upon user login and stored in the browser's local storage, which is functioning properly. The challen ...

Combining the revealing module pattern with the features of ES6 modules

I'm unsure about the best approach when it comes to using ES6 modules and the revealing module pattern. Is the data/functionality in an ES6 module as secure as in an IIFE? Should I stick with just ES6 modules, like this: // Export file export const ...

When specifying a width of '**' in the UI grid columns, they collapse unexpectedly

I'm currently working on a project involving the use of UI-Grid to display a list of users. I've set a width of "**" for each column in the column definition. However, when the output is rendered, all the columns appear collapsed on the left side ...