10

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?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Ludwig Magnusson
  • 13,964
  • 10
  • 38
  • 53
  • This seems like an objectively answerable question, that indeed has been answered. I don't understand the rationale for closing this as 'primarily opinion-based'. The OP is clearly opinionated, and some might argue that his "problem" isn't truly one, but he is nonetheless not *seeking* opinions from others, but asking a straightforward factual question. I am voting to reopen. – Mark Amery Feb 09 '15 at 22:42
  • My two cents: it's fundamentally at odds with AngularJS's design philosophy to object to having controller functions that are tied to handling particular DOM events. You'll sometimes want to have controller functions that take an `$event` and do something with it (like stopping propagation or checking a click target or something) and in those cases the function-purely-as-handler pattern is unavoidable. Just accept it, and if you need to reuse logic, extract it out into a different function that your handler calls. – Mark Amery Feb 09 '15 at 23:13

2 Answers2

32

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.

eddiec
  • 7,608
  • 5
  • 34
  • 36
0
 ng-disabled="regForm.$invalid || regForm.$pending"

hope this will be useful for you

Rajesh
  • 642
  • 2
  • 7
  • 14