为什么" preLink"函数用于角度指令`ngForm`,而不是常规" postLink"功能?

时间:2015-01-19 14:53:39

标签: angularjs angularjs-directive angularjs-ng-form

在angular.js中,在ngForm(form)指令定义中,compile函数只返回preLink函数。为什么它应该是preLink而不是普通postLink

以下代码来自angular.js master分支:

var formDirective = {
  name: 'form',
  restrict: isNgForm ? 'EAC' : 'E',
  controller: FormController,
  compile: function ngFormCompile(formElement) {
    // Setup initial state of the control
    formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
    return {
      pre: function ngFormPreLink(scope, formElement, attr, controller) {
        // if `action` attr is not present on the form, prevent the default action (submission)
        if (!('action' in attr)) {
          // we can't use jq events because if a form is destroyed during submission the default
          // action is not prevented. see #1238
          //
          // IE 9 is not affected because it doesn't fire a submit event and try to do a full
          // page reload if the form was destroyed by submission of the form via a click handler
          // on a button in the form. Looks like an IE9 specific bug.
          var handleFormSubmission = function(event) {
            scope.$apply(function() {
            controller.$commitViewValue();
            controller.$setSubmitted();
          });
        event.preventDefault();
        };
        ...

1 个答案:

答案 0 :(得分:2)

预链接函数在任何子指令之前执行,因此它是准备子指令使用的任何数据的好地方。我假设在这种情况下,它准备提交处理程序,以防子指令在其后链接函数中提交表单。

实际上,链接功能的执行顺序是:

  1. parent pre-link
  2. 儿童预先链接
  3. child post-link
  4. parent post-link