I have a form element created with AngularJS with a submit button within it and I would like to put this button outside of this form. How can I do that with Angular and have my
Even more concise than this answer:
<form name="myForm">
<input type="text" name="myField" required>
</form>
<button ng-disabled="myForm.myField.$invalid">
Submit
</button>
(Note that you don't even need to define myForm
in the underlying controller and you can also omit the form
attribute.)
As I understand You try to do form wizzard. However you don't need multiple form element, Just use one form element at the top. For child form use ng-form directive to valiadate them seperately.
You can find detailed documentation https://docs.angularjs.org/api/ng/directive/ngForm about using ng-form
Something like this
<form id="complateOrder" name="orderForm" ng-init="showShippingForm = true">
<div ng-form="" name="shipping" ng-show="showShippingForm">
shippig fields
<button type="button" ng-disabled="shipping.$invalid" ng-click="showDeliveryForm=true">Next</button>
</div>
<div ng-form="" name="delivery" ng-show="showDeliveryForm && shipping.$valid" ng-hide="shipping.$invalid" >
delivery fields
<button type="button" ng-disabled="shipping.$invalid && delivery.$invalid" ng-click="showPaymentForm=true">Next</button>
</div>
<div ng-form="" name="payment" ng-show="showPaymentForm && shipping.$valid && delivery.$valid " ng-hide="shipping.$invalid && delivery.$invalid">
payment fields
<button type="submit" ng-disabled="orderForm.$invalid && shipping.$invalid && payment.$invalid && delivery.$invalid">Submit All</button>
</div>
<div>
<button type="button" ng-click="showPaymentForm ? (showPaymentForm = false; showDeliveryForm= true):showDeliveryForm ? (showDeliveryForm=false; showShippingForm = true):showShippingForm = true">Prev</button>
</div>
</form>
The clue is using the ngForm directive and assign a form name attribute which references to the $rootScope.
<form name="$root.myForm" id="form_id">
<input type="text" name="myField" required>
</form>
<button form="form_id" ng-disabled="$root.myForm.myfield.$invalid">
Submit
</button>
That works.
If the submit button is outside of the form, then you can wrap your button and form with an ngForm (yes, ngForms can be nested). Give your ngForm a name so that you can handle the submit click and reference the form object by name in the same scope context