Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-submit does not allow custom binding on submit event

Tags:

angularjs

I have a directive I want to use to broadcast an event when a form is submitted.

The project I'm working on has a lot of forms, so it is not possible to broadcast the event in the function called by ng-submit.

Directive:

.directive('form', function() {
    return {
       restrict: 'E',
       link: function(scope, element, attrs) {
           element.bind('submit', function (e) {
               alert('some form submit');
               //trigger some event here later
           });
       },
    };
});

HTML:

<form data-ng-submit="saveForm()">
    //... some input elements
    <button type="submit">Save</button>
</form>

So, when a user clicks the button, the saveForm function is executed, but the event that was bound in the directive, to launch the alert, does not run. When I remove the ng-submit directive from the form-tag, the custom event-handler does work.

It looks like it is not possible to combine ng-submit and a custom event-handler?

Anyone has any solution for this behaviour?

like image 455
mantebridts Avatar asked Nov 27 '25 09:11

mantebridts


1 Answers

You can extend the built in ngSubmit directive and pass a secondary attribute to hook into the regular event.

Like so:

app.config(function ($provide) {

  $provide.decorator('ngSubmitDirective', function ($delegate, $parse) {

    var directive   = $delegate[0];
    var origCompile = directive.compile;

    directive.compile = function (el, attrs) {

      origCompile.apply(this, arguments);

      if (attrs.hook) {
        return function (scope, el, attrs) {
          var fn = $parse(attrs['ngSubmit']);   
          var hook = $parse(attrs['hook']);

          el.on('submit', function (event) {
            scope.$apply(function () {
              fn(scope,   { $event: event });
              hook(scope, { $event: event });
            });
          });          
        };
      }
    };

    return $delegate;
  });
});

This can then be used like so:

app.controller('ctrl', function () {
  $scope.fn = function () {
    console.log('regularFn');
  };

  $scope.hookFn = function ($event) {
    console.log('hookFn', $event);
  };
});

<form ng-submit="fn()" hook="hookFn($event)">
  <input type="submit">
</form>

JsBin for you: http://jsbin.com/qariqada/2/edit