$ http使用Angular 1.4.8中的rest Controller

时间:2016-05-04 21:57:58

标签: javascript angularjs

我最近刚接触AngularJS,我尝试在我的controller上使用别名来调用$http响应factory中的数据

我现在所做的就是它:

DiscoverService.js

var discoverService = angular.module('discover.services', []);

discoverService.factory('discoverV', function ($http) {
  return {
    list: function(callback){
      $http.get('https://myurl.com/get/jsondata').success(callback);
    }
  };
});

DiscoverCtrl.js

var discoverModule = angular.module('discover', ['discover.services']);

discoverModule.controller('discoverCtrl', [ '$scope', 'discoverV', function($scope, discoverV) {
  $scope.elm = [];

  discoverV.list(function(data) {
    $scope.elm = data;
  });
}]);

_discover.html

<div class="wrapper" ng-controller="discoverCtrl as discover">
  <article>
    <section id="block-stories" class="container" ng-repeat="element in elm">
      {{element.story_id}}
    </section>
  </article>
</div>

我一直在尝试这样做而且我不明白为什么下一段代码不起作用:

discoverModule.controller('discoverCtrl', [ 'discoverV', function(discoverV) {
  var elm = this;
  elm.videos = [];

  discoverV.list(function(data) {
    elm.videos = data;
  });

}]);

<div class="wrapper" ng-controller="discoverCtrl as discover">
  <article>
    <section id="block-stories" class="container" ng-repeat="element in discover.videos">
      {{element.story_id}}
    </section>
  </article>
</div>

我做错了什么?

感谢您的建议。

1 个答案:

答案 0 :(得分:3)

编写discoverCtrl as discover后,应使用discover访问控制器范围。

所以,你应该写一些类似的东西:

<div class="wrapper" ng-controller="discoverCtrl as discover">
  <article>
    <section id="block-stories" class="container" ng-repeat="element in discover.videos">
      {{element.story_id}}
    </section>
  </article>
</div>

我创建了一个示例(link),其中我只是模拟$http调用并且它有效(仅当您有其他错误时)。

希望它会有所帮助。