Skip to content

Instantly share code, notes, and snippets.

Created January 7, 2015 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/97efc4f2f12ba51c5cf3 to your computer and use it in GitHub Desktop.
Save anonymous/97efc4f2f12ba51c5cf3 to your computer and use it in GitHub Desktop.
Directive to show Bootstrap validation errors on submitting a form in AngularJS
app.directive('validSubmit', ['$parse', function ($parse) {
return {
// we need a form controller to be on the same element as this directive
// in other words: this directive can only be used on a <form>
require: 'form',
// one time action per form
link: function (scope, element, iAttrs, form) {
form.$submitted = false;
// get a hold of the function that handles submission when form is valid
var fn = $parse(iAttrs.validSubmit);
// register DOM event handler and wire into Angular's lifecycle with scope.$apply
element.on('submit', function (event) {
scope.$apply(function () {
// on submit event, set submitted to true (like the previous trick)
form.$submitted = true;
// if form is valid, execute the submission handler function and reset form submission state
if (form.$valid) {
fn(scope, { $event: event });
form.$submitted = false;
}
});
});
element.find('.form-group').each(function () {
var formGroup = $(this);
var inputs = formGroup.find('input[ng-model],textarea[ng-model],select[ng-model]');
if (inputs.length > 0) {
inputs.each(function () {
var input = $(this);
scope.$watch(function () {
return input.hasClass('ng-invalid') && (!input.hasClass('ng-pristine') || form.$submitted);
}, function (isInvalid) {
formGroup.toggleClass('has-error', isInvalid);
});
});
}
});
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment