简体   繁体   中英

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>

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

this in your controller and in $http are different because they are in different block of scope so assign this in another variable like _this and use it.

Try it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM