从指令

时间:2018-08-18 12:45:30

标签: angularjs

有人问过这种类似问题,我遵循了所有建议,但仍然无法触发指令提交。我具有用于多步骤表单验证的多个表单元素,并且有一个单击按钮来验证所有表单。这是html。

<form name="employeePersonalForm" ext-submit
      ng-submit="emp.submittedForm(employeePersonalForm)" novalidate>
   <div layout="row">
       <div class="default-form-item pr-3" ng-class="{'md-input-invalid': employeePersonalForm.$submitted && employeePersonalForm.firstName.$invalid}" flex>
           <label class="default-label required">First Name {{employeePersonalForm.firstName.$invalid}} - {{employeePersonalForm.$submitted}}</label>
            <div class="default-input-wrapper">
                <input ng-model="emp.firstName" class="default-input" name="firstName" type="text" required>
                <p class="default-input-error">This field is required</p>
            </div>
       </div>
       <div class="default-form-item pl-3" flex>
           <label class="default-label required">Last Name</label>
           <div class="default-input-wrapper">
               <input ng-model="emp.lastName" class="default-input" type="text" required>
                <p class="default-input-error">This field is required</p>
           </div>
       </div>
    </div>
</form>

此类型的多种形式存在于页面中。并且有一个如下所示的外部按钮。

<button class="default-btn default-btn--green" type="button" ng-click="nextStep($event)">Next</button>

单击“下一步”按钮时,我正在广播事件以提交表单。这是控制器部分。

emp.submittedForm = function(form) {
    if($scope.step==1) {
        alert(form.employeePersonalForm.$valid ? 'Valid' : 'Invalid!!!');
    }
}
$scope.nextStep = function() {
    if($scope.step == 1) {
        $rootScope.$broadcast('makeSubmit', {formName: 'employeePersonalForm'})
    }
};

我正在如下指令ext-submit中捕获此事件

(function () {
'use strict';

angular
    .module('app')
    .directive('extSubmit', ['$timeout', externalSubmit]);
/* @ngInject */
function externalSubmit($timeout) {
    return {
        link: function(scope, el, attr) {
            scope.$on('makeSubmit', function(event, data){
              if(data.formName === attr.name) {
                $timeout(function() {
                    el.triggerHandler('submit');
                }, 0, false);   
              }
            })
        }
    };
  }
})();

但是它不会触发ng-submit。我遵循了这个建议this link

1 个答案:

答案 0 :(得分:1)

一种方法是简单地执行ng-submit属性中的函数:

app.directive('extSubmit', ['$timeout', externalSubmit]);
/* @ngInject */
function externalSubmit($timeout) {
    return {
        require: "form",
        link: function(scope, elem, attrs, form) {
            scope.$on('makeSubmit', function(event, data){
              if(data.formName === attrs.name) {
                //SET submitted state
                form.$setSubmitted();
                //EVALUATE ng-submit
                scope.$eval(attr.ngSubmit);
                //$timeout(function() {
                //    elem.triggerHandler('submit');
                //}, 0, false);   
              }
            })
        }
    };
  }
})

有关更多信息,请参见