4

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?

4 Answers 4

12
<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.

Sign up to request clarification or add additional context in comments.

3 Comments

I see. The ng-required directive tries to directly access a variable in the scope named by the given string literal. Once It evaluates {{test}} to "true" it tries to find scope.true and this is undefined. Undefined is not == true, so it is not required. Thanks for that!
The result of an interpolation is always a string.
@JM. you are the guy!
5

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]" />

2 Comments

I did tried ng-required = "{true : 'true', false : 'false'}[test]" as your suggested but I curious why ng-required="{{test}}" does not work?
@Yoo in the Angular Directives, you don't have to wrap your expressions with the double brackets '{{}}' because it's already done. You have to it on non-Angular parameters however, like 'name', 'class', 'id' ...
1

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.

1 Comment

Could you explain why ng-required="user.name == ''" is not enough?
0

for some reason, both answers does not work, just use

ng-required="expired"

with expired to be a variable.

1 Comment

The accepted says exactly the same. Please read it more carefully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.