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 + ")"}}
?
This jsfiddle presents 4 options. choose whatever suits you better:
http://plnkr.co/edit/Su6udFHxIVEWmEpvulXZ?p=preview
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.
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
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.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.