Vinodh
Vinodh

Reputation: 5268

How to add form validation which populated using directive in angular js?

Am developing a registration form in AngularJS . In which am reusing the same form at 4 different places. For that am using a common form at single html page like the below.

<div>
   <div>
        <div class="label-div float-left">
            <label>
                Address:
             </label>
            <input type="text" ng-model="addressInfo.addressLine1" />
        </div>
   </div>
</div>

In my registration using the directive of AngularJS am reusing it in 4 different place like below

<registration-form></registration-form>
<input type="button" value ="continue" >

How can i disable button in registration html since my directive template has my form content .

Upvotes: 0

Views: 307

Answers (1)

ms87
ms87

Reputation: 17492

I would place the submit button inside the directive, and handle the ng-click event of the submit button by passing it through the scope of the directive

scope:{
onSubmit;'&'
}

inside your directives link function:

scope.submit=function(){
scope.onSubmit();
}

and your directive template:

<div>
   <form name="contactsForm">
        <div class="label-div float-left">
            <label>
                Address:
             </label>
            <input type="text" ng-model="addressInfo.addressLine1" />
            <input type="button" value ="continue" ng-click="submit()" ng-disabled="contactsForm.$invalid" >
        </div>
   </form>
</div>

usage:

<registration-form on-submit="postToServer()"></registration-form>

and in your parent controller, put any logic you want to execute when the form is submitted:

$scope.postToServer=function(){
alert("posting to server");
}

EDIT

Plunk.

EDIT 03/02-2014, another way would be to pass a flag from the directive to the parent controller indicating whether the form is valid or not, see how the "outer button"'s ng-disabled is hooked up in the plunk (I've updated it.)

Upvotes: 1

Related Questions