1

I have the following scenario; I have two functions that are actioned from a button:

<button ng-click="functionOne || functionTwo()"></button>

now I want to optimise a bit that and I want to call these functions only when they return something, anything , otherwise I don't want to be called and to return null or something. Now I'm wondering if is possible to use ternary operator having something like:

<button ng-click="condition ? functionOne || functionTwo() : null"></button>

calling the functions only when condition is true.

I have tested and is not really worked :|

7
  • 5
    You can't determine whether a function will return something without actually running it... Commented Sep 7, 2017 at 15:49
  • please add what functionOne is doing? Commented Sep 7, 2017 at 15:50
  • @NinaScholz is looking if there are some notifications and if there are should call the function to clear all notifications. Commented Sep 7, 2017 at 15:51
  • is functionOne a flag or a function? if function, you need to call it. Commented Sep 7, 2017 at 15:55
  • 1
    if functionOne() is falsy, you want to call functionTwo()? Commented Sep 7, 2017 at 15:58

1 Answer 1

2

You can pass the condition as an argument into the function, and then the function will check it. If it's true, it will do something, otherwise, it will do nothing.

Isn't that cleaner?

<button ng-click="functionTwo(condition)"></button>

and

$scope.functionTwo = function (conditon) {
  if (condition) {
    //do what you want...
  }
};

I suppose you wanted functionOne to return your condition in your original question. You can alter that as you wish.

Here is an example of what I'm describing:

https://codepen.io/anon/pen/EvBVqE

If you insist on using a ternary operator then you can do this, however I believe it's more complicated:

https://codepen.io/anon/pen/qXzbBJ

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

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.