AngularJS ng - don't need to work with variables

I need to use the ng-required directive, but I cannot hardcode true or false. I need to use it in a variable, but angular does not recognize "true".

JsFiddle example

<div ng-app ng-init="test=true"> <div> both have ng-required="true" <br/> one as hardcoded string literal, one via a variable <br/> Inspect them, one is not required! </div> <form name="myForm"> <input type="text" ng-required="{{test}}" /> <input type="text" ng-required="true" /> </form> </div> 

How can I make this work?

+4
source share
4 answers
 <input type="text" ng-required="{{test}}" /> 

You do not need to interpolate the test here. Since you want to evaluate the value of the test, just remove the curly braces and it should work.

+12
source

Just discovered yesterday, you can use the ng-required in the same template as the ng-class:

 <input type = "text" ng-required = "{true : 'true', false : 'false'}[test]" /> 
+5
source

Personally, I use ternary operators in these directives, and it works well. For the required ng:

 <input type="text" ng-required="(user.name == '' ? 'true' : 'false')" ng-model="user.nickname"/> 

In this example, if the username field is blank, the alias field becomes REQUIRED.

+1
source

for some reason both answers are not working, just use

 ng-required="expired" 

with the expired value for the variable.

0
source

Source: https://habr.com/ru/post/1487448/


All Articles