Last active
August 29, 2015 14:19
-
-
Save typesafe/e413f74fcb4b7bc12f50 to your computer and use it in GitHub Desktop.
ngSubmit with $attempted directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
AppModule.directive('ngSubmit', function () { | |
var thiz = this; | |
thiz.submit = function (ev, scope, el, attr) { | |
el.removeClass('shake'); | |
var frmController = scope[attr.name]; | |
frmController.$attempted = true; // can be used to provide visual feedback | |
if (frmController.$invalid) { | |
el.find('.ng-invalid')[0].focus(); | |
el.addClass('shake'); | |
scope.$apply(); | |
} else { | |
el.off(); | |
el.append(progressElement); | |
var promise = scope.$eval(attr.ngSubmit); | |
if (promise && promise.then) { | |
promise.then(function () { | |
el.on('submit', function (ev) { thiz.submit(ev, scope, el, attr); }); | |
}, function () { | |
el.on('submit', function (ev) { thiz.submit(ev, scope, el, attr); }); | |
}); | |
} else { | |
el.on('submit', function (ev) { thiz.submit(ev, scope, el, attr); }); | |
console.error("No promise was returned in method: \n" + attr.ngSubmit); | |
} | |
} | |
} | |
return { | |
restrict: 'A', | |
priority: 1, // important, make sure this directive is applied after the angular one so we can tweak it | |
compile: function (element, attributes, transclude) { | |
return { | |
post: function (scope, el, attr) { | |
el.off(); // thanks to priority | |
el.on('submit', function (ev) { thiz.submit(ev, scope, el, attr); }); | |
} | |
}; | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment