2

I'm having troubles with a simple idea. How do I remove the "Hello" when the user clicks the input field to only show the text that they are typing.

I need the "Hello" in the H1 tag to stay and only disappear when the user clicks the input field to start typing.

<div>
  <label>Name:</label>
  <input type="text" ng-model="yourName" placeholder="Enter a name here">

  <h1>Hello {{yourName}}</h1>
</div>

I have tried using jquery to empty or detach the H1 tag but that takes away the expression also.

Thank you for your help.

4 Answers 4

7

You could do it within the binding syntax:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app>
  <label>Name:</label>
  <input type="text" ng-model="yourName" placeholder="Enter a name here">

  <h1>{{yourName || 'Hello'}}</h1>
</div>

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

3 Comments

this is best answer to the question.
Perfect! Essentially the || makes the value null so Hello doesn't appear anymore?
@BradleySmith no. empty string is falsy, so the || behaves like javascript's || and returns the right handside.
1

you can keep the hello text into one span and give it a class.

<span ng-if="yourName">hell0</span>

Comments

1

Use another variable

<h1>{{ myLabel }}{{yourName}}</h1>

and then in controller

$scope.myLabel = 'Text as you please'; //'' to clear

Comments

-2

Wrap your Hello inside a span as:

<div ng-app>
  <label>Name:</label>
  <input type="text" ng-model="yourName" placeholder="Enter a name here">

  <h1><span id="temp">Hello </span>{{yourName}}</h1>
</div>

Now you can write this jquery to make your functionality work:

    $("input").focus(function(){
        $("#temp").hide();
    })

    $("input").blur(function(){
        $("#temp").show();
    })

Link attached now:http://codepen.io/Sky-123/pen/jrLBRA

Hope this helps!!

8 Comments

this is not an angular way.
@Aakash - Yes ofcourse your code works, There are numbers ways to acheive the goal. but we take only the smartest way like Daniel answered.
Angular way was not asked. Had it been asked that way, my solution would have been different. Hope it helps somebody. @ni3aj
Agree. Cheers!! @SudharsanS
I don't think that Daniel's functionality is implementing the solution properly. I mean the requirement was I need the Hello in the H1 tag to stay and only disappear when the user clicks the input field to start typing. In Daniel's solution, on clicking the input box Hello still stays. Once you start typing, then it goes away.Correct me if I am wrong @SudharsanS
|

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.