9

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

2 Answers 2

21

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.

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

6 Comments

except you can't use ternary operator in angular this way.
this will give you a lexer error : Lexer Error: Unexpected next character at columns 18-18 [?] in expression [ ownername.length ? ownername + "'s " : "" ].
@Quad AngularJS has supported the ternary operator for more than a year
@sabhiram sorry was not aware my test was using 1.1.x, upvoted answer
ternary will work but it's almost always a bad idea to add logic to your view. @theJoeBiz is right, this is exactly what angular filters are for.
|
4

Use a filter!

app.filter('possessive', function() {
  return function(val) {
    if (!val) return '';
    return val + '\'s';
  };
});

Then:

<h2>{{ ownername | possessive }} Online Bookshop</h2>

1 Comment

This worked for me. I needed to change true/false to yes/no on a bool.

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.