submit不允许对提交事件进行自定义

submit不允许对提交事件进行自定义

本文介绍了ng-submit不允许对提交事件进行自定义绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条指令,希望在提交表单时用于广播事件.

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

我正在处理的项目具有很多形式,因此无法在ng-submit调用的函数中广播事件.

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('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>

因此,当用户单击按钮时,将执行saveForm函数,但是在指令中绑定的用于启动警报的事件不会运行.当我从表单标签中删除ng-submit指令时,自定义事件处理程序确实可以正常工作.

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.

似乎无法将ng-submit和自定义事件处理程序组合在一起?

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

有人对此行为有解决方案吗?

Anyone has any solution for this behaviour?

推荐答案

您可以扩展内置的ngSubmit指令,并传递辅助属性以挂接到常规事件中.

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

像这样:

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: http://jsbin.com/qariqada/2/edit

这篇关于ng-submit不允许对提交事件进行自定义绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:08