angularjs 从Angular 中删除空值js选择选项

a64a0gku  于 2022-10-31  发布在  Angular
关注(0)|答案(2)|浏览(202)

我有一个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",
}]

我使用selectas在视图中填充此数据,

<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

我如何删除中间名中的空值并只显示Apple Jolie。

vql8enpb

vql8enpb1#

使用ternary operator

<select ng-options="… as (invigilator.firstName + ' ' + (invigilator.middleName !== null ? (invigilator.middleName + ' ') : '') + invigilator.lastName) for …"></select>

由于表达式变得非常复杂,您还可以(最好)将以下代码移到函数中:
第一个

ubof19bj

ubof19bj2#

一个简单的方法,使用数组。join [invigilator.firstName,invigilator.middleName,invigilator.lastName].join(' ')。这样你就不用担心任何值的情况下,如果它是空的。
示例演示: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>

相关问题