2014-10-16 54 views
0

在阅读约mocking server dependancies in JS and AngularJS apps后,我正在重构我的小型AngularJS应用程序中的主控制器。在AngularJS中使用ng-repeat调用和迭代函数返回值

在我的标记我遍历使用ng-repeat指令中的“主要事件”:

这是我的AngularJS模块,重构库和控制器。

但是我无法以这种方式访问​​主事件数组 - 我错过了什么?

// Module 
var app = angular.module('MainEventApp', ['cloudinary']); 

// Repository 
app.service('MainEventRepository', ['$http', function($http) { 

    this.$http = $http; 

    this.getMainEvents = function() { 

     return [ 
     { 
      id: 1, 
      roman_numeral: 'I', 
      name: 'Hulk Hogan & Mr T vs Rowdy Roddy Piper & Paul Orndorff', 
      venue: 'Madison Square Garden', 
      state: 'New York', 
      attendance: 19121 
     }, 
     { 
      id: 2, 
      roman_numeral: 'II', 
      name: 'Hulk Hogan vs King Kong Bundy', 
      venue: 'Split-Transmission', 
      state: 'New York/Illinois/California', 
      attendance: 40085 
     } 
     ]; 
    }; 

}]); 

// Controller 
app.controller("MainEventCtrl", ['$scope', 'MainEventRepository', function ($scope, MainEventRepository) { 

    MainEventRepository.getMainEvents().then(function(main_events) { 
     //$scope.main_events = main_events; 
     return main_events; 
    });  

}]); 

我的实时应用程序可以看到here(尚未重构)。

+0

请附上您的标记。如果将方法应用于'this',则需要在路由器或ng控制器中使用controllerAs语法。 – Martin 2014-10-16 17:18:25

回答

1

首先,要在您的标记中使用main_events,您需要在控制器范围中拥有此属性。

二,您的服务返回简单的数组,但在您的控制器中,您使用它,就好像它会返回诺言一样。

所以,你的控制器代码应该是临客这样的:

app.controller("MainEventCtrl", ['$scope', 'MainEventRepository', function ($scope, MainEventRepository) { 

    $scope.main_events = MainEventRepository.getMainEvents(); 

}]); 

而且你的标记:

<li ng-repeat="event in main_events"></li> 
0

您必须将main_events添加到您的范围。

MainEventRepository.getMainEvents().then(function(main_events) { 
    //$scope.main_events = main_events; 
    return main_events; 
}); 

为什么该诺言中的第一行注释掉了?