Ognjen Galić
Ognjen Galić

Reputation: 2742

Angular not updating view in $http.get().then()

This is my template:

<p>{{$ctrl.status}}</p>

This is the component:

var phoneListModule = angular.module("phoneListModule");

phoneListModule.component("phoneList", {

    templateUrl: "phone-list/phone-list.template.html",

  controller: function PLController($http) {

    this.status = "testing";

    $http.get("http://localhost/data.json").then(function(response) {
        self.status = "again";
    });

  }

});

And this is the module:

var phoneListModule = angular.module("phoneListModule", []);

The problem is that, the view is compiled properly with the "testing" text, but it's never updated to "again" when the GET request completes.

A console.log confirms that it completed fine

console.log(self.status);

Inside of the then() method.

Why is the view not updating if the dataset has changed?

Upvotes: 1

Views: 107

Answers (2)

Ognjen Galić
Ognjen Galić

Reputation: 2742

self is not defined inside of the then() function, you need to define it at the start of the controller.

var phoneListModule = angular.module("phoneListModule");

phoneListModule.component("phoneList", {

    templateUrl: "phone-list/phone-list.template.html",

  controller: function PLController($http) {

    var self = this; <<<< THIS IS IMPORTANT

    this.status = "testing";

    $http.get("http://localhost/data.json").then(function(response) {
        self.status = "again";
    });

  }

});

Upvotes: 2

AlainIb
AlainIb

Reputation: 4708

i think you should avoid using this or self because depending where you are ( like inside function or loop ) it means something different. Try with a variable pointing on this in the beggining of controller

phoneListModule.component("phoneList", {

    templateUrl: "phone-list/phone-list.template.html",

  controller: function PLController($http) {

    var vm = this ;
    vm.status = "testing";

    $http.get("http://localhost/data.json").then(function(response) {
        vm.status = "again";
    });

  }

});

Upvotes: 0

Related Questions