1

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>
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
suMi
  • 1,536
  • 1
  • 17
  • 30

2 Answers2

1

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

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
0

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);
  });
}
Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68