Skip to content

Instantly share code, notes, and snippets.

@B3nCr
Forked from anonymous/gist:97efc4f2f12ba51c5cf3
Last active August 29, 2015 14:13
Show Gist options
  • Save B3nCr/bbbe48a951e2cd366911 to your computer and use it in GitHub Desktop.
Save B3nCr/bbbe48a951e2cd366911 to your computer and use it in GitHub Desktop.
Angular directive which prevents form submit if it's not valid and sets Bootstrap classes
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);
});
});
}
});
}
};
}]);
@zackyang000
Copy link

Great job. Im looking for this, it's helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment