下划线组使用服务器数据

时间:2014-06-02 16:17:18

标签: javascript json angularjs underscore.js

我正在使用Angular.js和Underscore.js

我的控制器看起来像这样:

var facultyControllers = angular.module('facultyControllers', []);
facultyControllers.controller('FacultyListCtrl', ['$scope','FacultyListFactory', function($scope, FacultyListFactory) {
  //Get json from the server using factory
  $scope.speakers = FacultyListFactory.query();

  //GroupBy last name letter for the index
  $scope.groups = _.groupBy($scope.speakers['faculty'], "lastNameStartsWith");
}]);

我的观点如下:

<section id="faculty-list">
    <div ng-repeat="(lastNameStartsWith, speakers) in groups">
       <h3 id="{{lastNameStartsWith}}" class="faculty-list-header">{{lastNameStartsWith}}</h3>
       <article class="faculty-list-repeater" ng-repeat="speaker in speakers | filter: facultyFilter | orderBy:'last'">
           <div class="row">
           ...
           <div class="col-xs-10">
               <ul class="faculty-short-detail list-unstyled">
                  <li class="name">{{speaker.displayAs}}</li>
                  ...
               </ul>
           </div>
           </div>
        </article>
    </div>
</section>

来自服务器的json格式如下:

{
    "faculty":[
    {displayAs: 'John', lastNameStartsWith: 'A', firstName:'John', age:25, gender:'boy'},
    {displayAs:'Jessie', lastNameStartsWith: 'E', age:30, gender:'girl'},
    {displayAs:'Johanna', lastNameStartsWith: 'F', age:28, gender:'girl'},
    {displayAs:'Joy', lastNameStartsWith: 'F', age:15, gender:'girl'},
    {displayAs:'Mary', lastNameStartsWith: 'G', age:28, gender:'girl'},
    {displayAs:'Peter', lastNameStartsWith: 'L', age:95, gender:'boy'},
    {displayAs:'Sebastian', lastNameStartsWith: 'O', age:50, gender:'boy'},
    {displayAs:'Erika', lastNameStartsWith: 'T', age:27, gender:'girl'},
    {displayAs:'Patrick', lastNameStartsWith: 'V', age:40, gender:'boy'},
    {displayAs:'Samantha', lastNameStartsWith: 'Z', age:60, gender:'girl'}
    ]
};

我遇到的问题是当我做一个console.log($ scope.speakers);它做了一个资源,然后阵列在教师之下。如果我将上面的json直接放到我的控制器中代替FacultyListFactory.query();我可以运行$ scope.groups = _.groupBy($ scope.speakers [&#39; faculty&#39;],&#34; lastNameStartsWith&#34;);成功。但是我无法将它直接放入我的控制器,因为它们有数百个而且它们来自服务器。如果我运行$ scope.groups = .groupBy($ scope.speakers [&#39; faculty&#39;],&#34; lastNameStartsWith&#34;);尝试访问服务器我在控制台日志中得到一个对象,但它似乎是空的,我运行了console.log( .groupBy($ scope.speakers [&#39; faculty&#39;],&# 34; lastNameStartsWith&#34));

如果我运行$ scope.groups = _.groupBy($ scope.speakers,&#34; lastNameStartsWith&#34;);我得到了未定义,因为数据在{&#34; faculty&#34;:[...]}

我不确定如何在来自GET调用的数据的密钥值下访问嵌套数组。我需要按照此列表的姓氏字母进行分组,并且我一直试图让它工作几个小时。我不确定为什么教职员工会这样做。不工作。请帮忙!感谢

1 个答案:

答案 0 :(得分:0)

$scope.groups = _.groupBy(...);应该在query()的成功回调中,以便在返回数据后运行...

$scope.speakers = FacultyListFactory.query(function (data) { 
    $scope.groups = _.groupBy($scope.speakers['faculty'], "lastNameStartsWith"); 
}, function(error) { // error handler });