angular: modifying a variable within an http request callback

Dealing with an http call in my controller, where I am loading a json file, seems easy but hasn't been so far. Despite successfully updating the variable (console.log) in JS, it doesn't reflect in the html. Is there a way to incorporate $apply or similar to update the result? Any other suggestions? Here's a (not) working plnkr

JS:

    function SomeController($http){
  this.someValue = 'initial';
  $http.get('test.json').then(function (data) {
    this.someValue="changed";
    console.log("get request "+this.someValue);
  });
}

app.controller('someController', SomeController);

HTML:

<div ng-controller="someController as some">
      <p>{{some.someValue}}</p>
    </div>

Answer №1

When a function is created, it establishes its own unique this (context). In the scenario of using $http.get, the this within the success function does not refer to the context of the SomeController function. To resolve this issue, you need to store the context of the SomeController function in a variable like self, and then utilize that variable within the success callback of the $http.get function, allowing the this to be recognized as a global variable.

Controller

function SomeController($http){
  var self = this;
  self.someValue = 'initial';
  $http.get('test.json').then(function (data) {
    self.someValue = "changed";
    console.log("get request " + this.someValue);
  });
}

Demo Plunkr

Answer №2

this within your controller and in $http have different scopes, so it's best to assign this to another variable like _this and use that instead.

Give it a try!

function AnotherController($http){
  var _this = this;
  _this.someValue = 'initial';
  $http.get('test.json').then(function (data) {
    _this.someValue = "changed";
    console.log("get request " + _this.someValue);
  });
}

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

Integrate Geometric Information into PostGIS

Hi there! I'm currently using a combination of postgresql and node.js for my backend operations. I've been trying to insert a point into the database from the frontend, but unfortunately, I keep encountering an error message stating "value too lo ...

The animation of a disappearing div with CSS is not stopping when hovering over it

Hello, I've been working on a snackbar feature that appears and disappears on a set timer but also needs to pause when hovered over. Unfortunately, the current setup with setTimeout and useState is causing issues with this functionality. I have looke ...

The div has extra white space at the bottom due to the Hide/Show content feature

Having trouble stretching a scrolling div to 100% of its parent container's height? The Hide/Show content feature is causing whitespace at the bottom of the div. Check out the jsfiddle here: http://jsfiddle.net/fkvftff2/1/ LATEST UPDATE: The issue a ...

Replace the term "controlled" with "unleashed" when utilizing the file type input

In my app, I have defined multiple states like this: const [state,setstate]=React.useState({headerpic:'',Headerfontfamily:'',Subheaderfontfamilty:''}) And to get an image from my device, I am using the following input: &l ...

Is it possible to transfer a variable to a modal window by clicking on a link?

Here is a link with sample data value "data-id" that I want to pass: <a href="#edit_task" data-toggle="modal" data-id="WAH"><i class="fas fa-edit fa-lg fa-fw"></i></a> Javascript code to open the modal and assign the data value to ...

obtaining third-party JavaScript libraries

I'm encountering an issue while deploying a small Flask app that incorporates JavaScript and Three.js library files on a live server. I am facing a 404 resource not found error when attempting to import the necessary three.js files in my app.js file. ...

Uncovering the Power of Shadow DOM within HTML

Lately, I've noticed a lot of buzz surrounding Shadow DOM. During a video I watched about the launch of Angular 2, the speaker kept mentioning Shadow DOM without much explanation. Can someone clarify what exactly Shadow DOM refers to? ...

extracting the HTML content from JavaScript and saving it into a standalone file

update When I click a link, a popup opens and I see all this HTML. The smile method is called when I click the link, and we append HTML in that method so that we can see it when the popup is opened. I moved it to a separate file something.component.html, ...

The AJAX (WCF) request encountered a Bad Request error with status code 400

Struggling to utilize "POST" Methods with WCF, I've found that my service only supports "GET" Methods. The challenge arises when attempting to use "POST" Methods to send Objects: Contract Overview: [ServiceContract] public interface Itest { [Web ...

"Having trouble with Set-Cookie Response Header not setting the cookie? It could be due to

My webpage is located at: http://localhost:4201/login When a user clicks on login, it sends a request to: http://localhost:4201/api/login/authenticate This request is then proxied to: The response from the proxy contains a set-cookie header with the f ...

Error: The function "validate" is not recognized (jQuery validation)

Whenever I try to run the script, I encounter this error that prevents it from working properly. An error occured: Uncaught ReferenceError: validate is not defined I attempted to call the function onsubmit from the tag and even experimented with placi ...

What sets React$Element apart from ReactElement?

Attempting to implement flow with ReactJS and needing to specify types for prop children. The article on Flow + React does not provide any information. Despite encountering examples using ReactElement (e.g), I received an error message from flow stating i ...

How to best access the current item when repeating over a transclusion in Angular?

Here is the directive I've created: transclude: true, scope: { items: '=' } ... <div class="row" ng-repeat="item in items"> <div class="col-xs-9"> <ng-transclude></ng-transclude> </div> </div> My ...

Is it possible to apply JavaScript object destructuring but make changes to certain values before assigning them to a new object?

After receiving movie data from an api, I am currently manually creating a new object with a subset of properties and modified values. Is there a more efficient way to achieve this using javascript/typescript object destructuring syntax? I specifically wa ...

Sluggish performance observed in Eclipse following the import of an angularjs project scaffolded with Yeoman

After generating a new AngularJS project using Yeoman, I noticed that it created a large project folder with almost 190Mb of node_modules libraries. I'm not sure if this is typical, but when I tried to import the project into Eclipse as a new JavaScri ...

What is the best method for importing OrbitControls into my three.js project?

I'm having trouble importing OrbitControls into my project. I included three.js and then attempted to import OrbitControls, but it's not functioning as expected. I added three.js to the HTML body using the following command: script src="https:/ ...

The RSS feed reader is currently malfunctioning

I'm having trouble loading an RSS feed from the following URL: http://solutions.astrology.com/scripts/it.dll?cust_id=aamfha&doc=daily07short/dailyshort.xml Here is the code I am using to try to read it: url = 'http://solutions.astrology.co ...

How to properly structure an array in JSON format for utilizing in the Google Charts API?

Noticed that integer values need to be integers in the json, however I am using strings. The original array structure is as follows: '[{"sctr":"Asset Managers","amount":"1586500"},{"sctr":"Auto Parts","amount":"1618000"},{"sctr":"Business Su ...

The function 'send' cannot be called as it is undefined (response is undefined) within Express.js

I have encountered a challenge while trying to pass a variable from my index.html to the database (maildata.js) through app.js (server) and retrieve the corresponding data. I have successfully retrieved the data from the database, but I am facing difficult ...

JS problem with using for and foreach loops in Node.js

I've been really stumped by this situation. Everything was running smoothly until 4 days ago when two of my cron daemon jobs suddenly stopped working. Instead of ignoring the issue, I decided to take the opportunity to rebuild and enhance the code. I ...