INT
INT

Reputation: 912

Angular Directive and $http get

I'm struggling with my getting my directive to populate with data from an api. If I feed it with regular json it works just fine, but if I use http get I get blanks (the response is fine in the console).

What's best practice in this scenario. I found something about watch, but does seem pretty dirty, no? Also not quite sure how it adheres to my scenario..

angular.module('contestantList', [])
  .directive('cContestantList', function() {
    return {
      scope: {},
      templateUrl: '/app/themes/pomgallery/contestant_list.html',
      replace: true,
      controller: 'ContestantListCtrl',
      controllerAs: 'ctrl'
    };
  })
  .controller('ContestantListCtrl', function($scope, $http) {

    $http({
      method: 'GET',
      url: '/wp-json/posts',
      params: {
        'filter[posts_per_page]': 3
      },
    }).
    success( function( data, status, headers, config ) {
      this.contestants = data; /* DOES NOT WORK */
    }).
    error(function(data, status, headers, config) {});

    /* WORKS */
    //this.contestants = [{ "title": "Nadine Shjölin, Solo Exhibition"},{"title": "Hello world!"}]; 
  });

angular.module('PomGallery', ['contestantList']);

Upvotes: 0

Views: 394

Answers (1)

charlietfl
charlietfl

Reputation: 171679

this doesn't have context of the controller within the success callback (different scope)

Try storing in variable first.

.controller('ContestantListCtrl', function($scope, $http) {
    var vm = this; // store reference to "this"
    $http({
      method: 'GET',
      url: '/wp-json/posts',
      params: {
        'filter[posts_per_page]': 3
      },
    }).
    success( function( data, status, headers, config ) {
      vm.contestants = data;
    })......

Upvotes: 2

Related Questions