本文介绍了为什么要使用“& prelink& amp;"函数用于角度指令ngForm中,而不是常规的" postLink& quot;功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在angular.js的ngForm(窗体)指令定义中,编译函数仅返回 preLink 函数.为什么它应该是 preLink 而不是常见的 postLink ?

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

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

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();
        };
        ...

推荐答案

预链接功能在任何子指令之前执行,因此是准备任何要由子指令使用的数据的好地方.我认为在这种情况下,它会准备一个提交处理程序,以防子指令在其后链接功能中提交表单.

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. 父级预链接
  2. 子预链接
  3. 子发布链接
  4. 父后链接

这篇关于为什么要使用“& prelink& amp;"函数用于角度指令ngForm中,而不是常规的" postLink& quot;功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 05:53