我正在显示一个示例员工数据表,我需要命令以姓氏命名。数据通过.JSON文件提供,名称只有一个字符串:
users.json
{
"id": 5,
"name": "Bob Smith",
"username": "Eloyn.Skilles",
"email": "smith.bob@bolly.biz",
"address": {
"street": "Rox Trial",
"suite": "Suite 2890",
"city": "Smashmouth",
"zipcode": "586041099",
"geo": {
"lat": "27.8718",
"lng": "21.8984"
}
},
"phone": "210.067.6132",
"website": "elvis.io",
"company": {
"name": "Johns Group",
"catchPhrase": "Configurable multimedia taskforce",
"bs": "generate enterprise etailers"
}
}
到目前为止,我已经能够将字符串分成两部分:
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)'
,但没有运气。
答案 0 :(得分:2)
orderBy也接受函数。
ng-repeat="user in userData | orderBy:getlastname"
$scope.getlastname = function(user) {
var name = user.name.split(' ');
return name[1];
}
答案 1 :(得分:0)
您可以在Array
Angular orderBy docs
function
,attribute name
或orderBy
所以在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
}
范围内的当前用户作为参数传递
答案 2 :(得分:0)
orderBy with a string是一个表达式,所以你可以包含函数,或者自定义函数可以作为参数而不是字符串提供。
<tr ng-repeat="user in userData | orderBy:'name.split(\' \')[1]'">