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 😉


Leave a Reply

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