Created
March 25, 2015 20:47
-
-
Save kentcdodds/47c76d3e579ae10b9c2d to your computer and use it in GitHub Desktop.
ng-form with ng-submit support
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
export default ngModule => { | |
ngModule.directive('ngForm', ngForm); | |
function ngForm(_) { | |
return { | |
restrict: 'E', | |
link: function(scope, element, attrs) { | |
if (!attrs.ngSubmit) { | |
return; | |
} | |
var formController = scope.$eval(attrs.name); | |
if (formController) { | |
formController.azSubmit = function() { | |
if (formController.$invalid) { | |
return undefined; | |
} | |
var context = scope; | |
if (attrs.hasOwnProperty('submitFormOnParent')) { | |
context = scope.$parent; | |
} | |
formController.azSubmitting = context.$eval(attrs.ngSubmit); | |
return formController.azSubmitting; | |
}; | |
element.on('keyup', function(event) { | |
if (event.which === 13 && fromApprovedSource(event.target)) { | |
submitFormFromEvent(event); | |
} | |
}); | |
var submitButton = element.find('[type=submit]'); | |
if (submitButton.length === 1) { | |
submitButton.on('keyup', function(event) { | |
if (event.which === 32 || event.which === 13) { | |
submitFormFromEvent(event); | |
} | |
}); | |
submitButton.on('click', submitFormFromEvent); | |
} else if (!_.isEmpty(submitButton)) { | |
throw new Error('Forms should only have one submit button'); | |
} | |
} | |
function submitFormFromEvent() { | |
formController.azSubmit(); | |
scope.$apply(); | |
} | |
function fromApprovedSource(target) { | |
// note, select doesn't work because it fires a keyup when you select an option :-( | |
var isSubmittingNodeType = target.nodeName === 'INPUT'; | |
return isSubmittingNodeType || isSubmitButton(target); | |
} | |
function isSubmitButton(target) { | |
var isButton = target.nodeName === 'BUTTON'; | |
return isButton && target.getAttribute('type') === 'submit'; | |
} | |
} | |
}; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment