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:""};
}
underdog
  • 4,447
  • 9
  • 44
  • 89

1 Answers1

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>
AlwaysALearner
  • 43,759
  • 9
  • 96
  • 78
  • 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? – underdog Nov 25 '13 at 07:12
  • @ShivangSarawagi I have updated the answer. Take a look here: http://stackoverflow.com/questions/12008580/a-ternary-in-angular-templates-angularjs – AlwaysALearner Nov 25 '13 at 07:19
  • can I use jquery for DOM manipulation with angularJS? like instead of ternary operator use the jquery hide, show method? – underdog Nov 25 '13 at 09:54
  • Ofcourse you can. But why to do that when there's a very simpler way of doing the same? – AlwaysALearner Nov 25 '13 at 09:56
  • @ShivangSarawagi You might like using Angular's `ngShow` or `ngHide` directive. – AlwaysALearner Nov 25 '13 at 09:58