Inline if/else statement ngClick AngularJS

I can't believe something this essential and easy was so hard to figure out with Angular. Googling like crazy I eventually came across this solution.

If you need to add a conditional statement if else inside the ng-click core directive, use the following structure:

ng-click="variable = (condition=='X' ? 'Y' : 'X')"

Basically I wanted to assign a value to a variable on the ngClick event. It's fairly simple to use ternary operators to output strings or classes, it wasn't so obvious to assign variables.

Move logic to Controller / Directive

I hear you, all logic should be in a controller or directive. The view is not the place to be, I agree. However, sometimes you might need this πŸ˜‰

About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.
7 comments

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*