Sandeep Thomas
Sandeep Thomas

Reputation: 4727

Attach brackets to angularjs variable value when binding

Im very new to AngularJS. I've a simple scenario as follows

When no value specified in the input where the ng-modal defined it should show the output as

Hi

But when some values specified in the input it should show as

Hi (Jack)

I tried this way

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app>
<div>Hi {{(username)}}</div>
<input type='text' ng-model='username'>
  </div>

But it doesnt shows the brackets as I specified in the expression {{(username)}}.

So how can I accomplish this.

Upvotes: 2

Views: 672

Answers (3)

muenchdo
muenchdo

Reputation: 2181

You need to add quotes around the parentheses, since they are strings you want to add before and after the input. To make sure we display nothing when the input is empty, we check the existence of username first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app>
<div>Hi {{username ? '(' + username + ')' : ''}}</div>
<input type='text' ng-model='username'>
  </div>

Upvotes: 2

Vasyl
Vasyl

Reputation: 1424

<div>Hi <span ng-if='username'>({{username}})</span></div>

Upvotes: 4

Krupesh Kotecha
Krupesh Kotecha

Reputation: 2412

here i have modified some code and it working properly

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app>
<div>Hi <span ng-show='username.length > 0'>({{username}})</span></div>
<input type='text' ng-model='username'>
  </div>

Upvotes: 0

Related Questions