[英]Underscore groupBy using server data
我正在將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 ['faculty'],“ lastNameStartsWith”); 成功。 但是我不能將其直接放入控制器中,因為它們有數百個,它們來自服務器。 如果我運行$ scope.groups = .groupBy($ scope.speakers ['faculty'],“ lastNameStartsWith”); 嘗試訪問服務器時,我在控制台日志中得到一個對象,但它似乎為空,我運行了console.log( .groupBy($ scope.speakers ['faculty'],“ lastNameStartsWith”)));
如果我運行$ scope.groups = _.groupBy($ scope.speakers,“ lastNameStartsWith”); 我不確定,因為數據在{“ faculty”:[...]}下
我不確定如何從來自GET調用的數據中訪問鍵值下的嵌套數組。 我需要按此列表的姓氏分組,而且我一直在努力使其工作數小時。 我不確定為什么“教職員工”沒有工作。 請幫忙! 謝謝
$scope.groups = _.groupBy(...);
應該在query()
的成功回調中,以便它在返回數據之后運行...
$scope.speakers = FacultyListFactory.query(function (data) {
$scope.groups = _.groupBy($scope.speakers['faculty'], "lastNameStartsWith");
}, function(error) { // error handler });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.