Fred
Fred

Reputation: 21

Can't bind promise data to view in angularjs

I have tried the examples found on stackoverflow, but I still getting nothing in my view. I can see the articleIds in the console but nothing in the view. Thanks you in advance for your help.

Here is my controller:

export class MainController {
    constructor ($http) {
        'ngInject';

        this.$http= $http;
        this.apiHost = 'http://localhost:5005/api/articles';
        this.getArticles();
    }

    getArticles() {
        var vm = this;
        this.$http.get(this.apiHost).then(function(result){
            vm.articles = result.data;
            vm.articles.forEach(function(item){
                console.log(item.articleId);
            });     
        });
    }
}

Here my view:

<div class="form-group">
  <label for="resumeId">Select article:</label>
  <select class="form-control" id="resumeId">
    <option ng-repeat="item in main.vm.articles" value="{{item.articleId}}">{{item.articleId }}</option>
  </select></div>

Upvotes: 1

Views: 179

Answers (1)

MeterLongCat
MeterLongCat

Reputation: 228

This has nothing to do with the promise, the HTML just references the wrong scope. In the $http callback you assign the result to vm.articles (where vm is the controller's scope), so articles is available at main.articles rather than main.vm.articles.

Change your ng-repeat to ng-repeat="item in main.articles" and it will work.

Upvotes: 1

Related Questions