2

I have a variable username and a variable userid.
I want to display the name and the id in brackets it in an input like this:

Name (ID)

In angularjs I do <input value="{{username}} ({{userid}})" /> which leads to an ugly () when username and userid are empty.

Is there an easier way than using ng-if to solve my problem.
Something like {{ username + "(" + userid + ")"}}?

2
  • What would you like to display if userid is null? Commented Jun 6, 2014 at 12:55
  • The value should be empty Commented Jun 6, 2014 at 12:56

2 Answers 2

6

This jsfiddle presents 4 options. choose whatever suits you better:

http://plnkr.co/edit/Su6udFHxIVEWmEpvulXZ?p=preview

  1. Use only angular expression:

    {{ name ? '(' + name + ')' : ''}}

I wouldn't use this most of the time, it's just the most straight forward way to do it if you don't need anything reusable.

  1. Create a filter to display the user id:

    app.filter('userIdDisplay', function () { return function (input) { return input ? '(' + input + ')' : ''; }; });

    {{ name | userIdDisplay }}

I'd use this if you have a very specific formatting that is more complicated than just the parenthesis

  1. Create a generic filter to display a string if some variable has a truthy value:

    app.filter('ifExists', function () { return function (input, variable) { return variable ? input : ''; }; });

    {{ '(' + name + ')' | ifExists:name }}

I'd use this for a strings with a simple display, like only adding parenthesis.

  1. Use ng-if or ng-show and wrap with a span:

    <span ng-if="name">({{ name }})</span>

This I'd use if it's not only string formatting, but you also want to display other directives or plain html tags conditionally.

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

Comments

3

You're going to need either the ng-if or an ng-show. If you want to keep the element visible maybe you can try this:

{{ username && userId ? (username + "(" + userid + ")") : "" }}

Might need to be edited to handle empty spaces/zeros.

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.