0

I am 100% new to AngularJS, and I am trying to set a condition for displaying a String. If the text the user enters starts with the letter a, it should display Hello {{name}}, welcome back! (where {{name}} binds to the name entered), otherwise the text should not appear. My code is as follows:

<!DOCTYPE html>
    <html data-ng-app="">
    <head>
        <title>Type Your Name</title>
    </head>
    <body>
        Please type your name:
        <br />
        <table><input type="text" data-ng-model="name" />
        </br>
        Hello {{name}}, welcome back!

        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js">
        </script>
    </body>
    </html>
2
  • Did my answer not solve your problem? I'd appreciate if you'd mark my answer as correct. Commented Jan 10, 2015 at 15:22
  • Thank you very much Peter, and sorry for the delayed reply. Your answer solved my problem 100% Commented Jan 11, 2015 at 17:28

1 Answer 1

3

You should use a ng-if and check if the first character is the letter a.

<div ng-app>
    <input type="text" data-ng-model="name" />
    <span ng-if="name.charAt(0) === 'a'">Hello {{name}}, welcome back!</span>
</div>

Fiddle here.

Do not use ng-show because it always renders the DOM element and hides it if conditions are not met, ng-if renders the DOM element if and only if the condition is met.

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

1 Comment

I see plenty of other places which suggest using ng-show for this. This answer needs more attention!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.