简体   繁体   中英

More than one function in ng-click directory using ternary operator

Is it possible to use ternary operator in ng-click directory and call more than one function? I mean something like that:

<div ng-click="a==1 ? func1() func2() : ''">

Yes, but see the ternary operator, as this link says:

You can also do more than one single operation per case, separating them with a comma, and enclosing them in parenthesis:

var stop = false, age = 23;

age > 18 ? (
    alert('OK, you can go.'),
    location.assign('continue.html') ) : (
    stop = true,
    alert('Sorry, you are much too young!') );

You can also do more than one operation during the assignation of a value. In this case, the last comma-separated value of the parenthesis will be the value to be assigned.

But, it's not a problem for you.

You can call functions via ternary operator.

(a == 1) ? function1() : function2();
(a == 1) ? function1(param1) : function2(param1); //with input params

But calling the one, as you posted will return syntax error. Try below;

(a == 1) ? (function1(),function2()) : "'";
(a == 1) ? (function() { function1(); function2() })() : "'";

Though it's possible, it's not clean & easily readable. My suggestion would be to try as below;

(a == 1) ? combinedFunction() : "'";  //Put function1 & function2 within this combined function

You can call the functions in conditional operator

<div ng-click="a==1 ? func1(func2()) : angular.noop() ">

angular.noop() is an empty function or put "null"

plnkr like here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM