Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs, ng-if to change text?

I'm given the following code

 <h2>{{ownername}} Online Bookshop</h2>
 <input placeholder="type your name" ng-model="ownername" >

Which outputs 'Online Bookshop'

and if I input 'Fred' it outputs 'Fred Online Bookshop'

Without using jQuery, and doing things the angular way, how would I change the code so that a possessive apostrophe and the letter s were added when input is not empty?

EG

Online Bookshop when input is empty, and

Fred's Online Bookshop when input contains 'Fred' string

like image 867
PrimeLens Avatar asked May 24 '14 18:05

PrimeLens


1 Answers

Remember that the scope is just a place where you can evaluate things. So thats exactly what we can do. The ? is a ternary operator of the form: (expression)?<true clause>:<false clause>; and is equal to:

if(expression) { <true clause>; }
else { <false clause>; }

Modified code:

<h2>{{ ownername.length ? ownername + "'s " : "" }}Online Bookshop</h2>
<input placeholder="type your name" ng-model="ownername" >

Edit: Even though this works, its probably better as others point out to hide the logic from the view. This can be done by calling a scope function, or applying a filter to the variable to transform it as expected.

like image 161
sabhiram Avatar answered Sep 22 '22 17:09

sabhiram