0

Ng-repeat in component can't show data charged from $http.then in controller. What am i doing wrong?

Service calling rest method in app.js:

    app.service('dataService', dataService);

    function dataService ($http) {

    return {
     loadData: loadData
    }        

    function loadData() {

      var promise = $http.get("http://example.com/channels").then(function (response) {

        res = response.data;

      });
      return promise;

    }

Loading data in component.js

function channelListController(dataService){

this.channels = [];
/** If i create var like this, this works, but i want load from http method:
 this.channels = [{id:1, name: "xxxxx", description: "xxxxxxx", sport:    "xxxx"}]**/

dataService.loadData().then(function(d) {

  console.log(d);  //This console.log is showing DATA correctly!
  this.channels = d; 
});

Trying to showing data in view:

<tr ng-repeat="channel in $ctrl.channels">
        <td>{{ channel.name }}</td>
        <td>{{ channel.sport }}</td>
(...)

(Deploying with http-server)

The channels are not showing in view. If i create a var with data named channels, in channelListController before catch http.method, channels are showing OK, but if i charge data into the ".then" in controller, i cant show anything. The trace get into .then, and the http get method is receiving data correctly, but i can't load data into 'channels' var.

THANKS!!

2
  • If you insist on using this.channels inside the callback you pass to then, you should bind that entire callback to this to make sure you're updating the correct variable (i.e. (function (d) { this.channels = d; }).bind(this)). Otherwise, this.channels is not updating the channels variable you expect it to be. Commented Dec 5, 2016 at 0:00
  • @miqid thanks, it's working! Commented Dec 21, 2016 at 23:25

1 Answer 1

0

Looks like your references are wrong. Following should fix it

function channelListController(dataService){

var that = this;
this.channels = [];
/** If i create var like this, this works, but i want load from http method:
 this.channels = [{id:1, name: "xxxxx", description: "xxxxxxx", sport:    "xxxx"}]**/

dataService.loadData().then(function(d) {

  console.log(d);  //This console.log is showing DATA correctly!
  that.channels = d; // use that instead of this
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.