10

I'm wondering if it's possible to use a ternary expression in the ng-click attribute. I don't want to use a separate controller function if possible.

It's a two button toggle setup - I can get a simple toggle working, but don't want a second click of the "off" button to turn back on.

The ternary in ng-click does not work (note the ternary in ng-class does work):

<button
    ng-click="allOn2==true ? allOn2 : !allOn2"
    ng-class="allOn2==true ? 'btn-green-on' : 'btn-green-off'">
ON</button>

Here's a more complete jsfiddle: toggler

2
  • Why not just use ng-switch? Commented Jun 19, 2014 at 18:10
  • Haven't learned about ng-switch yet but from a brief check it seems more like a multi-choice ng-show/hide. Thanks Commented Jun 19, 2014 at 19:07

2 Answers 2

5

You are not doing anything with the ternary expression. For it to be useful, assign it:

{{ var1 }} {{ var2}}
<button
    ng-click="var1 = (allOn2==true ? allOn2 : !allOn2)"
    ng-class="{'btn-green-on':allOn2, 'btn-green-off' : !allOn2}">
ON</button>

I'm not sure how you can use ternary expressions for ng-class though...

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

3 Comments

Ah... you're right. My fiddle doesn't show any ng-model to which I have bound the value of allOn, as in my project. But I can see why what you suggested works. I think I was confused becuase the ng-class requires you to "do nothing" i.e. just evaluate the expression to find the class. I need to have the on-click set the value of allOn explicitly, which I thought was just happening through evaluation of the expression. Thanks!
here's a link to the updated fiddle: link
Checking for a boolean value in a ternary is kind of redundant. allOn2==true ? allOn2 : !allOn2 can just be allOn2 = !allOn2.
0

You can use something as as a workaround for ternary

 ng-click="(AppliedApps!=null && Collapse('CollapsedAppliedApplications')) || 
(AppliedApps.length==0 && Collapse('CollapsedAppliedApplications'))">

Comments

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.