简体   繁体   中英

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?

<form-input is-invalid-on="(isTouched && !gs.data.name) || (gs.data.name.length > 50)"</form-input>

可以尝试使用()并检查gs.dataisTouched && (!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>

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.

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.

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