mcmwhfy
mcmwhfy

Reputation: 1686

Angular ternary operator ? with functions

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 :|

Upvotes: 1

Views: 1380

Answers (1)

Dimitrios Matanis
Dimitrios Matanis

Reputation: 926

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

Upvotes: 2

Related Questions