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:

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 😉

Tags:

7 Responses to “Inline if/else statement ngClick AngularJS”

  1. Alex July 16, 2015 at 9:43 am #

    It’s so stupid … “all logic should be in controller…” … Angular gives you this holy bunch of ng-click, ng-show, ng-everything and everyone is using it. Doesn’t they notice that this is also logic inside the view?

    • Rick August 11, 2015 at 1:13 pm #

      Agreed! 🙂

  2. Muhammed Athimannil February 3, 2016 at 11:31 am #

    In some cases it is useful solution 👍

  3. Alberto Vieira May 25, 2016 at 2:43 pm #

    ty 🙂

    • Rick May 27, 2016 at 2:47 pm #

      You’re welcome Alberto!

  4. Abhijan Pal June 13, 2017 at 1:19 pm #

    Its working. Thanks a ton!

    • Rick June 14, 2017 at 9:36 am #

      You’re welcome!

Leave a Reply

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