我有一个JSON对象,如下所示
[{
"id": 1,
"firstName": "Sam",
"middleName": "poller",
"lastName": "Aniston",
"address": "New York City",
}, {
"id": 2,
"firstName": "Apple",
"middleName": null,
"lastName": "Jolie",
"address": "Beverley Hills",
}, {
"id": 3,
"firstName": "Anna",
"middleName": "mary",
"lastName": "Dobrev",
"address": "London",
}]
我使用select as,
在视图中填充此数据 <div >
<select ng-model="invigilator" ng-options="invigilator.id as (invigilator.firstName+' '+invigilator.middleName+' '+invigilator.lastName) for invigilator in invigilatorList" ng- click="getinvigilator(invigilator)" class="form-control">
<option value="">Select Invigilator</option>
</select></div>
但我得到选项,
Sam poller Aniston
Apple null Jolie
Anna mary dobrev
如何从中间名中删除该null并仅显示Apple Jolie。
答案 0 :(得分:2)
<select ng-options="… as (invigilator.firstName + ' ' + (invigilator.middleName !== null ? (invigilator.middleName + ' ') : '') + invigilator.lastName) for …"></select>
由于表达式变得非常复杂,您还可以(并且最好)在函数中移动此代码:
<select ng-options="… as getFullName(invigilator) for …"></select>
// In the controller
$scope.getFullName = function (invigilator) {
if (invigilator.middleName === null) {
return invigilator.firstName + ' ' + invigilator.lastName;
}
return invigilator.firstName + ' ' + invigilator.middleName + ' ' + invigilator.lastName;
};
答案 1 :(得分:1)
使用array.join [invigilator.firstName,invigilator.middleName,invigilator.lastName].join(' ')
的简单方法。这样,如果其值为null,则无需担心任何值。
示例演示:http://plnkr.co/edit/JTczvhMaNEeujrWnothP?p=preview
<select ng-model="invigilator" ng-options="invigilator.id as [invigilator.firstName,invigilator.middleName,invigilator.lastName].join(' ') for invigilator in data">
<option value="">Select Invigilator</option>
</select>