javascript - Angular 无法访问指令属性

标签 javascript angularjs

我有以下带有指令的应用程序:

(function() {
  var app = angular.module('myFeed', []);



  app.directive("feedList", function(){
      console.log('in feed list directive');
      return {
          restrict: 'E',
          templateUrl: "/static/angular/phone-list/feed-list.template.html",
          cotrollerAs: 'myController',
          controller: function($http){




              var data = $.param({
                  grant_type: 'password',
                  username: 'test',
                  password: 'test',
                  client_id:'test',
                  client_secret:'test',
              });

              var config = {
                  headers : {
                      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                  }
              }

              $http.post('/o/token/', data, config)
              .success(function (data, status, headers, config) {
                  access_token = data['access_token'];
                  console.log(access_token);

                  $http({method: 'GET', url: 'api/posts/', headers: {'Authorization': 'Bearer '+access_token}}).then(function(response) {
                      this.posts = response.data;

                    });

              })
              .error(function (data, status, header, config) {
                  $scope.ResponseDetails = "Data: " + data +
                      "<hr />status: " + status +
                      "<hr />headers: " + header +
                      "<hr />config: " + config;
              });


              var header = {
                      headers : {
                          'Authorization': 'Bearer '+self.access_token
                      }
                  }



          },

      }
  });



})();

我在index.html中的指令如下所示:

<feed-list></feed-list>

模板如下所示:

<li ng-repeat="post in myController.posts>{{post}}</li>

如何获得 <feed-list>显示 this.posts 中设置的帖子?

最佳答案

JavaScript 函数中此更改的范围。保留对此的引用

var myController = this;

在 Controller 构造函数的开头,然后使用

myController.posts = response.data;

而不是

this.posts = response.data;

在你的http回调函数中。

关于javascript - Angular 无法访问指令属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39459271/

相关文章:

JavaScript 隐式强制转换

html - 如何将多个div居中并向左浮动?

angularjs - 在 AngularJS 中使用 promise 防止 ngRepeat 闪烁

angularjs - 我可以将 !important css 关键字与 Angularjs ng-style 指令一起使用吗?

javascript - 如何以 Angular 从 $http.json 请求返回转换后的数据?

javascript - angularjs 字符串和字符串树

javascript - Google Charts 每页仅显示一个图表

javascript - Javascript 中的 CSS

PHP相当于JavaScript的字符串拆分方法

javascript - 折叠一个空广告