【问题标题】:Angular Directive and $http getAngular 指令和 $http 获取
【发布时间】:2015-04-24 17:29:09
【问题描述】:

我正在努力让我的指令填充来自 api 的数据。如果我用常规的 json 提供它,它工作得很好,但如果我使用 http get 我得到空白(在控制台中的响应很好)。

在这种情况下最佳做法是什么。我发现了一些关于手表的东西,但看起来确实很脏,不是吗?也不太确定它如何符合我的方案..

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']);

【问题讨论】:

  • 你能把回复粘贴到这里吗?你里面一定有一些属性,比如{ "result": [{..//your data }] }

标签: angularjs http angularjs-directive get


【解决方案1】:

this 在成功回调中没有控制器的上下文(不同的范围)

先尝试存储在变量中。

.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;
    })......

【讨论】:

  • 啊,太好了!似乎有点倒退,但因为它有效,我很高兴:)
  • 是常见的 javascript 范围问题
猜你喜欢
  • 2019-03-24
  • 2014-06-22
  • 2016-07-02
  • 1970-01-01
  • 2017-06-05
  • 2016-12-02
  • 2019-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多