Skip to content

Instantly share code, notes, and snippets.

@sulco
Created March 14, 2016 19:04
Show Gist options
  • Save sulco/18c776f67fdef22fb894 to your computer and use it in GitHub Desktop.
Save sulco/18c776f67fdef22fb894 to your computer and use it in GitHub Desktop.
angular.module('myApp.formUtils')
.directive('submitIfValid', function () {
return {
restrict: 'A',
require: '^form',
link: function (scope, element, attrs, form) {
element.on('click', handleClick);
function handleClick() {
markFieldsAsDirty();
submitFormIfValid();
// since we've reacted to changes outside of angular's digest loop,
// we need to trigger it manually
scope.$apply();
}
function submitFormIfValid() {
if (form.$valid) {
// if the form is valid just run the function passed
// as a value of `submit-if-valid` attribute
scope.$eval(attrs.submitIfValid);
}
}
function markFieldsAsDirty() {
Object.keys(form)
// The `form` object has a bunch of keys on it
// - the ones with names starting with `$` are used for form's methods and state
// - the rest are references to specific form fields (field's name => key name)
// and these are what we're after:
.filter(function(key) {
return key.indexOf('$') === -1
})
// And now we mark all those fields as `$dirty`
.forEach(function(fieldName) {
return form[fieldName].$setDirty()
});
}
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment