Angular ternary expression that runs more than one line of code - javascript

so I have this example of code,
in one of my forms, it works perfectly.
ng-submit="
commentCtrl.edit(comment.id, comment.text);
comment.edit=false;
"
on the other hand, when I try to run multiple "commands" in a ternary ng-keyup, things go wrong, angular can't parse it.
ng-keyup="
($event.keyCode == 13 && !$event.shiftKey)
?
commentCtrl.edit(comment.id, comment.text);comment.edit=false
:
return"
also tried:
($event.keyCode == 13 && !$event.shiftKey)
?
commentCtrl.edit(comment.id, comment.text) && comment.edit=false
:
return"
help me please!

It's a bad practice to write such expressions inside of markup.
Anyway you can do it by putting the values into an array:
ng-submit="[commentCtrl.edit(comment.id, comment.text), comment.edit=false]"
ng-keyup="($event.keyCode == 13 && !$event.shiftKey)
? [commentCtrl.edit(comment.id, comment.text), comment.edit=false]
: 0"

Related

"Do nothings" as statment in Javascript Condition

I want a ternary operator in JavaScript to return nothing if the statment is false
I have tried this:
1 == 1 ? alert('YES') : '';
But I want to know if this is the right way to make a statments "DO NOTHING" depending on the condition.
No, use if.
if (1 == 1) {
alert('YES');
}
Don't abuse the conditional operator as a replacement for if/else - it's confusing to read. I'd also recommend always using === instead of ==.
If you really want to do it, && will be one way.
1 == 1 && alert('ALERTED');
1 == 2 && alert('NOT ALERTED');
It is single statement.
A condition after an AND operator is only run if the first is true. So it is like an if statement.
did you try a single line if statement without brackets?
if(1 == 1) alert('Yes');

Better way to write ngClass condition

I am trying to think of a cleaner way to write this condition:
[ngClass]="{
'class1':
image.isAvailable && (image.property !== true && !null),
'class2':
image.isAvailable && (image.property === true && !null)
}"
So image.property sometimes can be NULL, and I am trying to handle it...I know I'm missing something obvious but don't know what. Any help much appreciated
You could use safe navigation operator ?. with ternary operator.
[ngClass]="(image?.isAvailable && image?.property) ? 'class1' : 'class2'"
Safe navigation operator checks if a property is defined before trying to access it.
Update
OP's requirement - use neither of the classes if image?.isAvailable is undefined.
You could extend the ternary operator to one more level to check if image?.isAvailable is defined before applying the classes.
[ngClass]="image?.isAvailable ? (image?.property ? 'class1' : 'class2') : ''"
The empty string '' denotes empty class list if image?.isAvailable property is undefined.
This can be written like this:
[ngClass]="{
'class1':
image.isAvailable && !image.property),
'class2':
image.isAvailable && image.property)
}"
Also you can write like this:
[class.class1]="image.isAvailable && !image.property"
[class.class2]="image.isAvailable && image.property"

Using Both AND and OR in IF Statement

I'm working on a Google Spreadsheet adding scripts (Not formulas) and I am stuck on a problem.
I need to find a way to use something like this:
If (Product == "Shampoo" && (Box == "15" OR Box == "17"))
{
//Do Something...
}
Basically IF the product is a shampoo and the box it belongs to is either 15 or 17 then do something. I know doing a If (Product == "Shampoo" && Box == "15" OR Box == "17") will produce unexpected or bad results. How do we go about using an OR with AND in google scripting?
From what I understand Google Scripts are based on Javascript but I can't seem to find help posts online or here in SO, all I get are solutions in formula not script.
First a note about the OP code
JavaScript methods are case sensitive.
Instead of IF the correct syntax is if. By the other hand the Logical OR operator is ||.
Considering the above, the OP code could be replaced by
if(Product == "Shampoo" && (Box == "15" || Box == "17"))
{
//Do Something...
}
and
if(Product == "Shampoo" && Box == "15" || Box == "17")
Regarding the question, if (Product == "Shampoo" && Box == "15" || Box == "17") returns unexpected or bad results, this could be hard to read and lead to confusions for humans but JavaScript have very specific rules regarding how operations should be made by the engine, in this case Rhino which is used by Google Apps Script.
As was mentioned in a previous answer in this case the rule is called operator precedence but in order to make the code easier to read and to prevent confusions a good practice is to enclose each comparison in parenthesis.
Considering that the Logical AND has a higher precedence than Logical OR
(Product == "Shampoo" && Box == "15" || Box == "17")
is the same as
((Product == "Shampoo" && Box == "15") || Box == "17")
References
if..else
Logical OR
What are you looking for is the operator precedence of the two operators logical AND && and logical OR ||.
Part of the table:
Precedence Operator type Associativity Individual operators
---------- ------------- --------------- --------------------
6 Logical AND left-to-right … && …
5 Logical OR left-to-right … || …
You see a higher operator precendece of logical AND over logical OR. That means you need some parenthesis for the OR statement.

How to make true && false equal to true in angularjs expression?

I'm trying to check if an input has been touched and is empty (without the built in functions in angular).
<form-input is-invalid-on="isTouched && !gs.data.name || gs.data.name.length > 50"></form-input>
If isTouched && !gs.data.name evaluates to true && false then that side of the expression becomes false
So my question is quite simple, how do I make the entire expression evaluate to true if the input has been touched and if it's empty or has a length greather than 50?
I believe it is used as attribute directive.
is-invalid-on="(isTouched && gs.data.name.length) || gs.data.name.length > 50"
Reason? I assumed your gs.data.name is a string. Empty string when evaluated in javascript is still a truthy value. So you must evaluate it to length.
<form-input is-invalid-on="(isTouched && !gs.data.name) || (gs.data.name.length > 50)"</form-input>
can try using () and also check gs.data like isTouched && (!gs.data || !gs.data.name || !gs.data.name.length || gs.data.name.length > 50)
<form-input is-invalid-on="isTouched && (!gs.data || !gs.data.name || !gs.data.name.length || gs.data.name.length > 50)"></form-input>
Angular expression does not work exactly the same than javascript from what i got try this one :
<form-input is-invalid-on="isTouched && gs.data.name.length==0 || gs.data.name.length > 50"></form-input>
Assuming you properly initialized gs.data.name to empty string.
By the way you forgot the > on your tag.
I finally found the reason as to why it was behaving so strange, and as this question has many answers I could not delete it. So I might as well explain what happened.
It turned out that isTouched was always undefined because I was using it outside of the directive (even if it was used in an attribute of the directive) which made the expression undefined && false, resulting in isInvalidOn always being false.
Instead I made it so that I used isTouched later in the actual form-input template as ng-class={invalid: isInvalidOn && isTouched}, resulting in the desired behavior.

JavaScript shorthand if statement, without the else portion

So I'm using a shorthand JavaScript if/else statement (I read somewhere they're called Ternary statements?)
this.dragHandle.hasClass('handle-low') ? direction = "left" : direction = "right"
This works great, but what if later I want to use just a shorthand if, without the else portion. Like:
direction == "right" ? slideOffset += $(".range-slide").width()
Is this possible at all?
you can use && operator - second operand expression is executed only if first is true
direction == "right" && slideOffset += $(".range-slide").width()
in my opinion if(conditon) expression is more readable than condition && expression
Don't think of it like a control-block (ie: an if-else or a switch).
It's not really meant for running code inside of it.
You can. It just gets very ugly, very fast, which defeats the purpose.
What you really want to use it for is ASSIGNING VALUES.
Taking your initial example and turning it on its head a little, you get:
direction = (this.dragHandle.hasClass("handle-low")) ? "left" : "right";
See. Now what I've done is I've taken something that would have required an if/else or a switch, which would have been used to assign to that one value, and I've cleaned it up nice and pretty.
You can even do an else-if type of ternary:
y = (x === 2) ? 1 : (x === 3) ? 2 : (x === 4) ? 7 : 1000;
You can also use it to fire code, if you'd like, but it gets really difficult after a while, to know what's going where (see the previous example to see how even assignment can start looking weird at a glance)...
((this.dragHandle.hasClass("...")) ? fireMe(something) : noMe(somethingElse));
...this will typically work.
But it's not really any prettier or more-useful than an if or a branching, immediately-invoking function (and non-JS programmers, or untrained JS programmers are going to crap themselves trying to maintain your code).
The conditional operator is not a shorthand for the if statement. It's an operator, not a statement.
If you use it, you should use it as an operator, not as a statement.
Just use a zero value for the third operand:
slideOffset += direction == "right" ? $(".range-slide").width() : 0;
What you have will not work, but why not just use a one line if statement instead.
if(direction == "right") slideOffset += $(".range-slide").width();
This involves less typing than the method Ray suggested. Of course his answer is valid if you really want to stick to that format.
No, This is not possible, because ternary operator requires, three operands with it.
first-operand ? second-operand (if first evaluates to true) : third-operand (if false)
you can use && operator
direction == "right" && slideOffset += $(".range-slide").width()
This doesn't exactly answer your question, but ternaries allow you to write less than you've shown:
direction = this.dragHandle.hasClass('handle-low') ? "left" : "right";
And now that I think about it, yeah, you can do your question too:
slideOffset + direction == "right" ? = $(".range-slide").width() : = 0;
This is a theory. The next time I have an opportunity to += a ternary I will try this. Let me know how it works!
You can use this shorthand:
if (condition) expression
If in some cases you really want to use the if shorthand. Even though it may not be the best option, it is possible like this.
condition ? fireMe() : ""
Looks weird, does work. Might come in handy in a framework like Vue where you can write this in a template.
You can using Short-circuit Evaluation Shorthand. if you want the if condition just write the else condition.
let
a = 2,
b = a !== 2 || 'ok';
console.log(b);

Categories

Resources