Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent ng-submit from being called for an invalid form [duplicate]

If I have declared a form with a function tied to the ng-submit directive, how can I prevent that function from being executed when the submit button is clicked but the form is invalid?

I have found two solutions to this that has big drawbacks and therefore I do not want to use them:

  1. Pass in the form to the controller:

    //HTML
    <form ng-submit="myFunc($form, model)">
    
    //JavaScript
    $scope.myFunc = function($form, model) {
        if ($form.$valid) {
            //do stuff
        } 
    }
    

    This is bad since it ties the function to being called from a form.

  2. Make the submit button disabled when the form is invalid.

    <input type="submit" ng-disabled="!form.$valid"/>
    

    This is bad because disabled elements are hard to work with. Tooltips dont show when the button is hovered or clicked so it is hard to give feedback to a user trying to click the disabled button.

Is there another solution to this problem?

like image 657
Ludwig Magnusson Avatar asked Dec 03 '13 18:12

Ludwig Magnusson


1 Answers

It's possible to do this:

<form name="myForm" ng-submit="myForm.$valid && myFunc()">

But there's not much harm in checking the validity within ngSubmit itself.

like image 79
eddiec Avatar answered Oct 25 '22 18:10

eddiec