0

我正在显示样本员工数据表,并且我需要以姓为单。该数据是通过以.json文件提供,并且名称是一个字符串:如何使用分割字符串函数的结果与Angular.js进行排序?

users.json 

{ 
    "id": 5, 
    "name": "Bob Smith", 
    "username": "Eloyn.Skilles", 
    "email": "[email protected]", 
    "address": { 
    "street": "Rox Trial", 
    "suite": "Suite 2890", 
    "city": "Smashmouth", 
    "zipcode": "58604­1099", 
    "geo": { 
     "lat": "27.8718", 
     "lng": "21.8984" 
    } 
    }, 
    "phone": "210.067.6132", 
    "website": "elvis.io", 
    "company": { 
    "name": "Johns Group", 
    "catchPhrase": "Configurable multimedia task­force", 
    "bs": "generate enterprise e­tailers" 
    } 
} 

到目前为止,我已经能够分割字符串成两个:

MainController.js 

/* Function to split strings where there is a space present */ 
$scope.nameSplitter = function(string, index) { 
    $scope.array = string.split(' '); 
    return $scope.result = $scope.array[index]; 
} 

这里是HTML:

<table class="table table-striped table-bordered table-condensed table-hover"> 
    <th>Name</th> 
    <th>Email</th> 
    <th>Phone</th> 

    <!-- Would like to ideally orderBy last name --> 
    <tr ng-repeat="user in userData | orderBy:'name'"> 
     <td>{{ nameSplitter(user.name,1) }}, {{ nameSplitter(user.name,0) }}</td> <!--0 returns first name, 1 returns last name--> 
     <td><a ng-href="mailto:{{user.email}}" target="_blank">{{user.email}}</a></td> 
     <td><a ng-if="user.phone !== ''" href="tel:{{nameSplitter(user.phone, 0)}}" data-toggle="tooltip" title="{{nameSplitter(user.phone, 0)}}"> 
      <span class="glyphicon glyphicon-earphone"></span></a></td> 
</table> 

我试过这orderBy:'nameSplitter(user.name, 1)'与各种支架组合,但没有运气。

+2

您打算如何处理“边缘情况”单名(Pele),冠名加单名(教皇弗朗西斯),姓氏多部分(Ludwig van Beethoven),多个姓氏(EnriquePeñaNieto),多个名字(Sarah Jessica Parker)等。 ?如果可以的话,您应该考虑重组您的表格以包含首选姓氏,首选姓名,地址的首选形式......取决于您计划如何使用数据。 – shoover

+0

这是一个很好的观点。感谢您将此引起我的注意。我正在处理的这个项目中的数据很简单,幸运的是没有(也不会)包含边界情况。 –

回答

2

orderBy也接受函数。

ng-repeat="user in userData | orderBy:getlastname" 

$scope.getlastname = function(user) { 
    var name = user.name.split(' '); 
    return name[1]; 
} 
+0

这对我有效!问题是我不知道如何获得orderBy接受函数。谢谢! –

0

您可以使用ArrayfunctionorderByAngular orderBy docs

因此,一个attribute name在HTML

<tr ng-repeat="user in userData | orderBy:myCustomOrderBy"> 

,并在控制器

$scope.myCustomOrderBy = function(user){ 
    return user.name.split(' '); //what you intent to here play on your own 
} 

范围当前用户作为传递论点

0

orderBy与一个字符串是一个表达式,所以你可以包含函数,或者可以提供一个自定义函数作为参数而不是字符串。

<tr ng-repeat="user in userData | orderBy:'name.split(\' \')[1]'"> 
+1

你将不得不逃避那些单引号 – Ronnie

相关问题