Why a “preLink” function is used in angular directive `ngForm`, instead of regular “postLink” function?

允我心安 提交于 2019-12-08 12:41:57

问题


Inside angular.js, in ngForm (form) directive definition, compile function returns only a preLink function. Why it should be preLink instead of common postLink?

The following code is from angular.js master branch:

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:


The pre-link function is executed before any child directives so it's a good place to prepare any data to be used by child directives. I presume in this case it prepares the submission handler in case a child directive submits the form in its post-link function.

In practice the order of execution of link functions is:

  1. parent pre-link
  2. child pre-link
  3. child post-link
  4. parent post-link


来源:https://stackoverflow.com/questions/28027365/why-a-prelink-function-is-used-in-angular-directive-ngform-instead-of-regul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!