0

I have a JSON object which is as follows

[{
"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",
}]

I'm populating this data in view using 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>

But I am getting options as,

Sam poller Aniston
Apple null Jolie
Anna mary dobrev 

how can i remove that null from the middle name and show only Apple Jolie.

2 Answers 2

2

Use the ternary operator:

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

Since the expression is becoming pretty complex, you can also (and you'd better to) move this code in a function:

<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;
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks,it worked both ways. i am going for the using function in the controller .
1

A simple approach using array.join [invigilator.firstName,invigilator.middleName,invigilator.lastName].join(' '). This way you need not worry about any of the values incase if its null.

Sample demo: 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>

1 Comment

Nice, seems a quick approach.Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.