Here is a simple form with an input that is required:
<div ng-controller="MainCtrl">
<form name="add-entry" press-enter="add_entry()">
<input type="text" ng-model="amount" required />
<!-- <input type="submit" value="Add" /> -->
</form>
</div>
The form uses a custom pressEnter directive because I'm reluctant to use an <input type="submit" />
in my markup, even if I can hide it with absolute positioning and whatnot (using ngSubmit
instead of pressEnter
would require one of these to fire the expression).
angular.module('app', []).directive('pressEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if(event.which === 13) {
scope.$apply(function(){
scope.$eval(attrs.pressEnter);
});
event.preventDefault();
}
});
};
});
The problem now is that the required
attribute is also not taken into account without ngSubmit
. See http://jsfiddle.net/w6QHD/12/ -- you can see that pressing enter on an empty input still fires add_entry()
. The form is validated only when using ngSubmit
instead of pressEnter
and uncommenting the <input type="submit">
.
How do I make form validation work without using ngSubmit
?