-
-
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
This file contains hidden or 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
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
Great job. Im looking for this, it's helpful.