Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: String and variable in curly braces

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 + ")"}}?

like image 750
Horen Avatar asked May 09 '26 00:05

Horen


2 Answers

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.

like image 132
haimlit Avatar answered May 10 '26 14:05

haimlit


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.

like image 42
Mathew Berg Avatar answered May 10 '26 14:05

Mathew Berg