ngResource返回的值无法传递给控制器​​?

时间:2016-04-07 04:24:58

标签: angularjs

我有以下服务

eventservice.js:

angular.module('staApp')
.factory('EventsService', function($resource) { // Value returned correctly
    return $resource('http://....azurewebsites.net/api/events/getlist');
});

使用Chrome开发人员工具进行调试时,webapi调用会返回有效的json结果。

[{"Id":22,"EventName":"xxx","TimeStart":"2016-04-22T22:00:00","Price":0.0000,"ImageUrl":"~/Content/Event/thumb_07e3467d-f0a4-470b-91bc-523981fdcb82.png","VenueId":9572},
 {"Id":23,.....

在控制器events.js

angular.module('aApp')
  .controller('EventsCtrl', function ($scope, EventsService) {

    $scope.events = EventsService.query(); // The length of $scope.events is 0; tried get() but got a different error

    this.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];
  });

在Chrome中进行调试时,显示$scope.events的长度为零。为什么控制器无法获取数据?

视图代码为:

<h1>Title is shown in the page</h1>
<div ng-repeat="event in events" style=" background-image:url( {{event.ImageUrl}} )">
    test <!-- this only show once while five times are expected -->
    <div id="events-li-info_box">
        {{event.EventName}}
        <div class="events-li-info_bttm-row">
            {{event.TimeStart}} 
            {{event.Price}}
        </div>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

试试这个

angular.module('aApp')
  .controller('EventsCtrl', function ($scope, EventsService) {
   $scope.entries = EventsService.query(function() {
     console.log($scope.entries);
   })

    this.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];
  });

HTML视图:

<div ng-controller="EventsCtrl">
    <div ng-repeat="event in entries " class="back-cover" style=" background-image:url( {{event.ImageUrl}} )">
        <div id="events-li-info_box">
            {{event.EventName}}
            <div class="events-li-info_bttm-row">
                {{event.TimeStart}} 
                {{event.Price}}
            </div>
        </div>
    </div>

</div>