2

Using Angular, I would like to know how to add a space before, and a comma after {{name}} so that if there is not a name entered into the input, then the web page will just display: Hello ... BUT, if there is a name entered, the page will display: Hello Sarah,

How do I make that extra space and extra comma appear conditional to whether or not the name exists?

<h1>Hello {{name}},</h1>
<h1>Welcome to my website!</h1>
<h1>Please enter your name:</h1>
<input type="text" ng-model="name">

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

1 Answer 1

3

You can use ng-show:

<h1>Hello<span ng-show="name"> {{name}},</span></h1>

This will display the span if name is truthy. Since the span contains the extra space, the name itself, and the comma, only "Hello" will be displayed if name isn't set.

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

3 Comments

Perfect!! Do you know how would I get the input to disappear once a name is entered?
You can use ng-show on any HTML element, including the input. If you want the input to disappear after you enter a name, use this: <input type="text" ng-show="!name" ng-model="name" ng-model-options="{ updateOn: 'blur' }"> Note how I've set the model to update on blur... else it would disappear as soon as you type something.
Also, I discovered you can use { updateOn: 'change blur' } to enable the enter key to trigger the hide as well. Thanks Mike!

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.