0

I have an object that has 3 fields:

obj.firstName
obj.middleName
obj.lastName

I have an array (objArray) of these objects that I am showing in an ng-repeat like this:

<tr ng-repeat="obj in objArray">
    <td>{{ obj.lastName + ", " + obj.firstName + " " + obj.middleName }}</td>
</tr>

The problem is that I have some obj's that have null as a value for obj.middleName. Is there a way to not display null if part of the expression happens to be null? I see that you can use a filter to remove one element completely from the ng-repeat, but I still want to display an element that has firstName and lastName. I just want it so that it doesn't display like this:

Smith, John null

But rather just displays this:

Smith, John

3 Answers 3

2

You can use join

 <td>{{ [obj.lastName + ',' ,obj.firstName, obj.middleName].join(' ') }}</td>

JSFiddle Demo: http://jsfiddle.net/HB7LU/21495/

Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect and simple, I had never used join() before but this is great. Thanks!
1

Just wrap the parts in concern with a span with a ng-if. If it's null, the span will remove itself from the DOM.

<tr ng-repeat="obj in objArray">
    <td>{{ obj.lastName + ", " + obj.firstName }}<span ng-if="obj.middleName ">{{" " + obj.middleName }}</span></td>
</tr>

Comments

0

I would suggest creating a function on scope that takes as an argument one of your objects which then handles if any of the fields are null. This reduces the amount of template logic and keeps that "logic" in the controller rather than the specific view (template). Then you can use a span and an ng-bind expression that gets set to the return value of your function.

/* HTML */
<tr ng-repeat="obj in objArray">
    <td><span ng-bind="getDisplayName(obj)"></span></td>
</tr>


/* JS */
$scope.getDisplayName = function getDisplayName(obj) {
    var name = "";
    if (!obj) {
        return name;
    }

    if (obj.lastName) {
        name += obj.lastname + ", ";
    }

    if (obj.firstName) {
        name += obj.firstName + " ";
    }

    if (obj.middleName) {
        name += obj.middleName
    }

    return name;
}

Comments

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.