How to validate a form when the submit button is outside of this form, with angularJs?

后端 未结 4 1204
孤街浪徒
孤街浪徒 2021-02-08 11:47

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

相关标签:
4条回答
  • 2021-02-08 12:24

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

    0 讨论(0)
  • 2021-02-08 12:34

    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>
    
    0 讨论(0)
  • 2021-02-08 12:37

    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.

    0 讨论(0)
  • 2021-02-08 12:49

    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

    0 讨论(0)
提交回复
热议问题