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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With