2

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?

4

1 回答 1

3

目前还不清楚您是要依赖 HTML5 验证还是 AngularJS 验证。如果它是您想要使用的 Angular 验证,那么您可以简单地使用FormController来触发验证和错误消息:

<div ng-controller="MainCtrl">
  <form name="form" press-enter="add_entry()" novalidate>
    <input type="text" name="amount" ng-model="amount" required />
    <span ng-show="submitted && form.amount.$error.required">Amount is required</span>
  </form>
</div>
function MainCtrl($scope) {
    $scope.add_entry = function() {
        $scope.submitted = true;
        if($scope.form.$valid){
            console.log("Entry added");
        }
    }
};

小提琴

于 2013-07-12T11:51:19.140 回答