如何从angularjs指令取消表单提交

时间:2014-12-09 08:24:32

标签: angularjs angularjs-directive

我正在创建一个验证指令,当表单字段在表单中无效时会显示一条消息。如果字段无效,我想显示消息并取消提交。 我已成功通过要求ngModel和表单控制器显示提交的验证消息,但我似乎无法找到使用FormController取消表单提交的方法。 我已经准备好了一个问题here。 如您所见,它显示错误,但我无法阻止提交函数被触发。

// Code goes here

var directiveName = "fcValidate";
angular.module("app", [])
.directive(directiveName, ["$timeout", validatorDirective])
.controller("PageCtrl", [pageCtrl]);

function validatorDirective($timeout) {
    return {
        restrict: "A",
        require: ["^ngModel", "?^form"],
        link: link
    };

    function link(scope, element, attributes, controllers) {
        var modelCtrl = controllers[0];
        var formCtrl = controllers[1];

        // Validation.
        $timeout(run);

        function run() {
            var requiredMessage = "Please enter the %(field)s.",
                minLengthMessage = "Sorry, but the %(field)s cannot be shorter than %(minLength)s characters.",
                maxLengthMessage = "Sorry, but the %(field)s cannot be longer than %(maxLength)s characters.",
                minValueMessage = "Sorry, but the %(field)s cannot be less than %(min)s.",
                maxValueMessage = "Sorry, but the %(field)s cannot be greater than %(max)s.",
                invalidNumberMessage = "Please ensure that the %(field)s is a valid number.";

            var content = null;
            var field = attributes.name;
            if (!field) {
                return;
            }

            var toWatch = function () {
                if (formCtrl) {
                    return formCtrl.$submitted;
                }
                return modelCtrl.$error;
            };

            scope.$watchCollection(toWatch, function (newValues, oldValues) {
                var error = modelCtrl["$error"];
                var invalid = modelCtrl["$invalid"];
                var dirty = modelCtrl["$dirty"];

                if ((formCtrl && !formCtrl.$submitted) || (!formCtrl && (_.keys(newValues) === _.keys(oldValues))) || !invalid || !dirty) {
                    return;
                }

                var msgTpl = null;
                var fieldName = attributes[directiveName];

                if (fieldName) {
                    fieldName = fieldName.toLowerCase();
                }

                if (error.required) {
                    msgTpl = requiredMessage;
                } else if (error.minlength) {
                    msgTpl = minLengthMessage;
                } else if (error.maxlength){
                    msgTpl = maxLengthMessage;
                } else if (error.min) {
                    msgTpl = minValueMessage;
                } else if (error.max){
                    msgTpl = maxValueMessage;
                } else if (error.number) {
                    msgTpl = invalidNumberMessage;
                }

                if (fieldName) {
                    var data = {
                        field: fieldName || "",
                        min: attributes.min,
                        max: attributes.max,
                        minLength: attributes.minlength,
                        maxLength: attributes.maxlength
                    };

                    if (msgTpl) {
                        content = _.string.sprintf(msgTpl, data);
                    } else {
                        content = fieldName;
                    }
                }
                
                // Show message...
                alert(content);
                // Cancel the form submit here...
            });
        }
    }
}

function pageCtrl() {
  var vm = this;
  
  vm.user = {};
  
  vm.submit = submit;
  
  function submit() {
    console.log(vm.user);
  }
}
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.string/2.3.0/underscore.string.min.js"></script>
<script src="https://code.angularjs.org/1.3.5/angular.js"></script>
<body data-ng-app="app" data-ng-controller="PageCtrl as vm">
  <form data-ng-submit="vm.submit()">
    <input type="text" name="firstName" required="" minlength="2" placeholder="First Name" data-ng-model="vm.user.firstName" data-fc-validate="First Name" />
    <button type="submit">Submit</button>
  </form>
</body>

我的问题是,如何取消表单提交?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

如果它像jQuery一样,如果你将函数绑定到&#34;提交&#34;事件你只需要在回调中return false

答案 1 :(得分:0)

是否足够禁用提交按钮?如果是,请定义表单名称,然后在提交按钮

上的ng-disabled中使用它
<form data-ng-submit="vm.submit()" name="validatingForm">
    <input type="text" name="firstName" required="" minlength="2" placeholder="First Name" data-ng-model="vm.user.firstName" data-fc-validate="First Name" />
    <button type="submit" ng-disabled="validatingForm.$invalid">Submit</button>
</form>

此外,我认为ng-messages对您的验证消息非常有用 - https://docs.angularjs.org/api/ngMessages/directive/ngMessages