Created
March 14, 2016 19:04
-
-
Save sulco/18c776f67fdef22fb894 to your computer and use it in GitHub Desktop.
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
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