0

I am using a very simple code to bind the user text input to the model. The text box prompts the user to enter the name & says hello "username" on enter. But I also want Hello to appear only when the user enters the name. Can anyone help me with that. Currently Hello is present by default.

ui page

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script type="text/javascript" src="../js/prac_controller.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>prac_one</title>
</head>
<body ng-app>

<div ng-controller="pracOne">
Enter the name<br>
<input type="text" ng-model="message.text"/>
<p>Hello, {{message.text}}</p>
</div>
</body>
</html>

controller

function pracOne($scope)
{
$scope.message={text:""};
}

1 Answer 1

1
<p>{{message.text ? 'Hello, ' + message.text : message.text}}</p>   

Or

<p>{{message.text && 'Hello, '+message.text || message.text}}</p>

Update: You can use ngShow if you want to conditionally display an element:

<p><span ng-show="message.text != ''">Hello, </span>{{message.text}}</p>
Sign up to request clarification or add additional context in comments.

5 Comments

thanks for the reply; can u plz explain why && and || are used; is there any link from where I can refer. message.text will display whatever the user types then after that will the && do?
@ShivangSarawagi I have updated the answer. Take a look here: stackoverflow.com/questions/12008580/…
can I use jquery for DOM manipulation with angularJS? like instead of ternary operator use the jquery hide, show method?
Ofcourse you can. But why to do that when there's a very simpler way of doing the same?
@ShivangSarawagi You might like using Angular's ngShow or ngHide directive.

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.