【问题标题】:Why a "preLink" function is used in angular directive `ngForm`, instead of regular "postLink" function?为什么在角度指令`ngForm`中使用“preLink”函数,而不是常规的“postLink”函数?
【发布时间】:2015-01-19 14:53:38
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    实际上链接函数的执行顺序是:

    1. 父级预链接
    2. 子预链接
    3. 子帖子链接
    4. 父帖子链接

    【讨论】:

      猜你喜欢
      • 2013-10-26
      • 2013-02-24
      • 2018-11-19
      • 1970-01-01
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多