Search code examples
javascriptangularjsangularjs-controllerangularjs-controlleras

updating variable in http request callback in angular


This is probably easy but nevertheless. I have a http call in my controller where I load a json file. I want to update a variable in my html based on a result. It updates apparently the variable (console.log) in JS but not in the html. Is there a way to use $apply with the result or similar? What else to use? 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>

Solution

  • Whenever we create a function it has its own this(context). In your case this you're using inside $http.get success function is not this(context) of SomeController function. You have to keep the SomeController function context inside self variable & then use that variable in your success callback of $http.get function so that this will be treated 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