Search code examples
angularjsnested-formsrequired

Angular : make nested subform required (or not)


On one hand, i have a very simple emailForm directive.

script

directives.directive('emailForm', function(){
    return {
        restrict: 'AE',

        templateUrl: "views/forms/email.html",
        controller: function(){console.log('its the addressForm here dude');},
        scope: {
            email: '=email'
        },
        require: ['^form', 'ngModel']
    };
});

I now want to use this directive inside a contactForm :

<form name="contactForm">
   <input type="text" ng-model="contact.name"/>
   <email-form email="contact.email"></email-form> // how to make this required or not...?
</form>

How can i make the emailForm required in contactForm (not in the mail directive as i want to be able to use it somewhere where its not going to be required)?

My first thought was pass a required parameter in the emailDirective, but while this seems a good idea for a simple input (like email), it doesnt seem to be as soon as the nested subform is a real form on its own.


Solution

  • The required attribute is only valid for inputs tags. If you want to be able to switch all input fields in the sub form you can try something like :

    <email-form email="contact.email" form-required="<your value>"></email-form>
    
    //javascript emailFormDirective : 
    scope:{
        emailRequired:"@formRequired",
        email:"=email"
    } 
    
    //email.html template
    <input ... ng-required="emailRequired" ... />
    

    Note : i used differents names for every step so you won't get lost between them.