I'm creating an angular directive which attaches to an angular form and modifies it's submit behaviour. The idea is to check validity and do a few things if the form isn't valid (show errors, scroll page etc). I have found some code to help with this but I can't seem to find how to re-create the ng-submit and make the form actually post if the form is valid. I have my own version of the ng-submit attribute which works like this - six4-submit="myController.myfunction()" so I guess it's a case of evaluating the angular expression inside the success part of my directive?
Here is the full code so far with a comment where the code needs to go.
.directive('six4Form', function($log) {
return {
restrict: 'A',
scope: {
six4FormSubmit: '@',
},
require: 'form',
compile: function(element, attrs) {
// Auto set novalidate
if (!attrs.novalidate) {
element.attr('novalidate', '');
attrs.novalidate = true;
}
return {
// In the pre-compilation section so it gets run before
// any other submit functions.
pre: function(scope, element, attrs, formCtrl) {
// Submit function
element.bind('submit', function(event) {
if (formCtrl && !formCtrl.$valid) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
}
// Form IS valid
else {
// Code here should evaluate contents if attrs.six4FormSubmit and run it
}
});
}
}
}
};
});
EDIT: Let me re-phrase the question as it's causing some confusion...
If I were to write ng-submit="mySubmit()" then the ngSubmit directive must be doing something to evaluate the expression it contains and find the mySubmit function on the scope and run it. I simply want to emulate that behaviour in my directive. Unfortunately I can't find the ngSubmit code in the Angular github repo.
EDIT 2: Getting there
Looking at the code for ng-submit it appears that something like this should work
var callback = $parse(attrs.six4FormSubmit);
scope.$apply(function() {
callback(scope, {$event:event})
});
Unfortunately it doesn't and it's hard to debug as it produces no errors, it just doesn't run the callback function whereas ng-submit does.