AngularJS ng-required not working with variables

16,333

Solution 1

<input type="text" ng-required="{{test}}" />

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

Solution 2

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

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

Solution 3

Personally I use ternary operators into these kind of directives, and it works well. For the ng-required :

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

In this example, if the name field of the user is not filled, the nickname field become REQUIRED.

Share:
16,333
Admin
Author by

Admin

Updated on June 22, 2022

Comments

  • Admin
    Admin about 2 years

    I have to use the directive ng-required, but I cannot hardcode true or false. I need to use it in a variable, but angular does not recognize the "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 get this working?