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>
share|improve this question
up vote 1 down vote accepted

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

share|improve this answer

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);
  });
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.