0

I have a form with AngularJS validation. The problem is that I add validators in a elements dynamically:

if (constraint.NotNull){
    elem.attr("ng-required","true");
}

The NgModelController for this element always evaluate "form.$valid = true", even with empty value.

What's wrong?

1 Answer 1

1

You don't need to add the attribute dynamically. If you read carefully enough on AngularJS API reference for ngRequired, you will learn that the value for ngRequired can be binded. The example there is the best.

https://docs.angularjs.org/api/ng/directive/ngRequired

In your case create

$scope.isRequired = { field1: true, field2: false, ... }

You can change this dynamically and AngularJS will reflect that.

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

4 Comments

tank u, your solution save my life. But i'm not understand yet, why my solution not works.
It didn't work because you would have to re-render the view or do a digest cycle to reflect it in the DOM.
Petr, help me please. How make a re-render view or do a digest cycle? I tried "$compile(content.contents())(scope));", but not work. The form Angular is always invalid, same valid.
Try $scope.apply().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.