Angular.js源码分析之compile编译

上一篇提到了angular中编译compile部分,下边就来一起看看其详细的实现过程。

首先来找找$compile服务这个是在什么时候定义的,找到核心模块ng中一段代码:

angularModule('ng', ['ngLocale'], ['$provide',
  function ngModule($provide) {
    // 省略
    // 创建$compile的$CompileProvider
    $provide.provider('$compile', $CompileProvider)
      .directive({
            a: htmlAnchorDirective,
            input: inputDirective,
            //省略
      })
    // 省略
  }
])

所以说这里要分析的是$CompileProvider以及为啥能直接链式调用directive的问题(注意到了吗?$provide是没有directive方法的,所以注定是$provide.provider()的返回值有directive方法)。

首先来看下$CompileProvider的代码:

/**
 * 核心 compile
 */
$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
function $CompileProvider($provide, $$sanitizeUriProvider) {
  var hasDirectives = {}, // 保存所有的指令
      Suffix = 'Directive',
      COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
      CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
      ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
      REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;

  // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  // The assumption is that future DOM event attribute names will begin with
  // 'on' and be composed of only English letters.
  var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  // 省略
  this.directive = function registerDirective(name, directiveFactory) {
    // 省略
  };
  // 省略
  var debugInfoEnabled = true;
  this.debugInfoEnabled = function(enabled) {
    if (isDefined(enabled)) {
      debugInfoEnabled = enabled;
      return this;
    }
    return debugInfoEnabled;
  };

  this.$get = [
            '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
            '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
    function($injector,   $interpolate,   $exceptionHandler,   $templateRequest,   $parse,
             $controller,   $rootScope,   $document,   $sce,   $animate,   $$sanitizeUri) {

    // 省略
  }];
}

到这里就能解释了上边的第二个疑问了,调用$provide.provider('$compile', $CompileProvider)的时候直接实例化了$CompileProvider这个构造函数了,在之前注入器文章中分析了provider的实现:发现$CompileProvider是一个函数,所以直接调用了注入器实例的instantiate,他就是以构造函数的形式来执行了$CompileProvider,所以说这里就能调用在其中的this.directive方法了。

directive方法

这里就先分析下这个directive,看看到底做了什么事情:

// 解析独立绑定
// 包括独立scope的情况
// 和bindToController的情况
// 主要是对 @ = & 这样的语法进行parse
function parseIsolateBindings(scope, directiveName, isController) {
  var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;

  var bindings = {};

  forEach(scope, function(definition, scopeName) {
    var match = definition.match(LOCAL_REGEXP);

    if (!match) {
      throw $compileMinErr('iscp',
          "Invalid {3} for directive '{0}'." +
          " Definition: {... {1}: '{2}' ...}",
          directiveName, scopeName, definition,
          (isController ? "controller bindings definition" :
          "isolate scope definition"));
    }

    bindings[scopeName] = {
      mode: match[1][0],
      collection: match[2] === '*',
      optional: match[3] === '?',
      attrName: match[4] || scopeName
    };
  });

  return bindings;
}

function parseDirectiveBindings(directive, directiveName) {
  var bindings = {
    isolateScope: null,
    bindToController: null
  };
  if (isObject(directive.scope)) {
    // 独立scope
    // bindToController设为true
    if (directive.bindToController === true) {
      // 这里做一次替换,把scope的内容当做是bindToController内容
      bindings.bindToController = parseIsolateBindings(directive.scope,
                                                       directiveName, true);
      // 设置其isolateScope的值为一普通对象 没有绑定的任务
      bindings.isolateScope = {};
    } else {
      // 默认绑定到scope
      bindings.isolateScope = parseIsolateBindings(directive.scope,
                                                   directiveName, false);
    }
  }
  // bindToController是对象的话
  // 把其内容绑定到controller上
  // 和绑定到scope上的语法一样 
  if (isObject(directive.bindToController)) {
    bindings.bindToController =
        parseIsolateBindings(directive.bindToController, directiveName, true);
  }
  if (isObject(bindings.bindToController)) {
    var controller = directive.controller;
    var controllerAs = directive.controllerAs;
    // 用了bindToController就必须有controller和controllerAs
    if (!controller) {
      // There is no controller, there may or may not be a controllerAs property
      throw $compileMinErr('noctrl',
            "Cannot bind to controller without directive '{0}'s controller.",
            directiveName);
    } else if (!identifierForController(controller, controllerAs)) {
      // There is a controller, but no identifier or controllerAs property
      throw $compileMinErr('noident',
            "Cannot bind to controller without identifier for directive '{0}'.",
            directiveName);
    }
  }
  return bindings;
}

function assertValidDirectiveName(name) {
  var letter = name.charAt(0);
  if (!letter || letter !== lowercase(letter)) {
    throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
  }
  if (name !== name.trim()) {
    throw $compileMinErr('baddir',
          "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
          name);
  }
}

/**
 * 注册新的指令
 */
 this.directive = function registerDirective(name, directiveFactory) {
  assertNotHasOwnProperty(name, 'directive');
  if (isString(name)) {
    // key value 形式
    assertValidDirectiveName(name);
    assertArg(directiveFactory, 'directiveFactory');
    if (!hasDirectives.hasOwnProperty(name)) {
      // 还没有name的Directive工厂
      hasDirectives[name] = [];
      // 加后缀Directive
      $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
        function($injector, $exceptionHandler) {
          // 此时使用的时候
          // 取得所有的directiveFactory然后执行
          // 得到的就是要如何构建指令的对象(指令对象)
          var directives = [];
          forEach(hasDirectives[name], function(directiveFactory, index) {
            try {
              var directive = $injector.invoke(directiveFactory);
              if (isFunction(directive)) {
                directive = { compile: valueFn(directive) };
              } else if (!directive.compile && directive.link) {
                directive.compile = valueFn(directive.link);
              }
              // 指令对象的配置属性们
              directive.priority = directive.priority || 0;
              directive.index = index;
              directive.name = directive.name || name;
              directive.require = directive.require || (directive.controller && directive.name);
              directive.restrict = directive.restrict || 'EA';
              // 解析scope(bindToController)绑定
              var bindings = directive.$$bindings =
                  parseDirectiveBindings(directive, directive.name);
              if (isObject(bindings.isolateScope)) {
                // 独立scope对象
                directive.$$isolateBindings = bindings.isolateScope;
              }
              // 指定directive的$$moduleName
              // 也就是在moduleInstance对象上暴露directive的时候使用的是
              // invokeLaterAndSetModuleName 给directiveFactory赋值了$$moduleName
              directive.$$moduleName = directiveFactory.$$moduleName;
              directives.push(directive);
            } catch (e) {
              $exceptionHandler(e);
            }
          });
          return directives;
        }]);
    }
    // 添加
    hasDirectives[name].push(directiveFactory);
  } else {
    // 批量注册 指令
    forEach(name, reverseParams(registerDirective));
  }
  return this;
};

从上边可以看出在调用directive的时候其实是会创建一个以name+Suffix为名的service的(通过$provide.factory的方法),也就意味着同一个名字的指令可以有多个directiveFactory的,也就说我们可以一直增强同一个指令。这个在angular的源码中也有用到多个directiveFactory的情况,也就是ng-include这个指令,这里暂不分析他了,因为后面会对一些特殊指令再去进行分析。

言归正传,这里可能顺便看下这个新的service的内容了,从上边代码可以看出,angular便利了所有的该指令的directiveFactory,然后去构建封装计算好的单个directive对象,然后push进了directives数组中返回了。

compile

从之前的分析可以确定的是当需要provider实例的时候会去执行定义时指定的$get方法,所以说compile编译的关键还是要看其中的内容:

// Attributes属性封装
var Attributes = function(element, attributesToCopy) {
  if (attributesToCopy) {
    var keys = Object.keys(attributesToCopy);
    var i, l, key;

    for (i = 0, l = keys.length; i < l; i++) {
      key = keys[i];
      this[key] = attributesToCopy[key];
    }
  } else {
    this.$attr = {};
  }

  this.$$element = element;
};

Attributes.prototype = {
  // 原型中方法
};


function safeAddClass($element, className) {
  try {
    $element.addClass(className);
  } catch (e) {
    // ignore, since it means that we are trying to set class on
    // SVG element, where class name is read-only.
  }
}

// 省略

compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  var bindings = $element.data('$binding') || [];

  if (isArray(binding)) {
    bindings = bindings.concat(binding);
  } else {
    bindings.push(binding);
  }

  $element.data('$binding', bindings);
} : noop;

// 静态方法 增加ng-binding的class
compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  safeAddClass($element, 'ng-binding');
} : noop;
// 静态方法 给元素设置scope数据
compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  $element.data(dataName, scope);
} : noop;
// 静态方法 增加scope的class
compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
} : noop;

return compile;

//================================

// 核心编译
function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  // 省略
}

首先看下Attributes,可以看到的是基本上是把元素属性上的键值对增加到了this上,然后他还有一堆的原型方法,这里看下:

Attributes.prototype = {

  $normalize: directiveNormalize,

  $addClass: function(classVal) {
    if (classVal && classVal.length > 0) {
      $animate.addClass(this.$$element, classVal);
    }
  },

  $removeClass: function(classVal) {
    if (classVal && classVal.length > 0) {
      $animate.removeClass(this.$$element, classVal);
    }
  },

  $updateClass: function(newClasses, oldClasses) {
    var toAdd = tokenDifference(newClasses, oldClasses);
    if (toAdd && toAdd.length) {
      $animate.addClass(this.$$element, toAdd);
    }

    var toRemove = tokenDifference(oldClasses, newClasses);
    if (toRemove && toRemove.length) {
      $animate.removeClass(this.$$element, toRemove);
    }
  },
  
  // 设置属性key的值为value
  $set: function(key, value, writeAttr, attrName) {
    // TODO: decide whether or not to throw an error if "class"
    //is set through this function since it may cause $updateClass to
    //become unstable.

    var node = this.$$element[0],
        booleanKey = getBooleanAttrName(node, key),
        aliasedKey = getAliasedAttrName(key),
        observer = key,
        nodeName;

    if (booleanKey) {
      this.$$element.prop(key, value);
      attrName = booleanKey;
    } else if (aliasedKey) {
      this[aliasedKey] = value;
      observer = aliasedKey;
    }

    this[key] = value;

    // translate normalized key to actual key
    if (attrName) {
      this.$attr[key] = attrName;
    } else {
      attrName = this.$attr[key];
      if (!attrName) {
        this.$attr[key] = attrName = snake_case(key, '-');
      }
    }

    nodeName = nodeName_(this.$$element);

    if ((nodeName === 'a' && key === 'href') ||
        (nodeName === 'img' && key === 'src')) {
      // sanitize a[href] and img[src] values
      this[key] = value = $$sanitizeUri(value, key === 'src');
    } else if (nodeName === 'img' && key === 'srcset') {
      // sanitize img[srcset] values
      var result = "";

      // first check if there are spaces because it's not the same pattern
      var trimmedSrcset = trim(value);
      //                (   999x   ,|   999w   ,|   ,|,   )
      var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
      var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;

      // split srcset into tuple of uri and descriptor except for the last item
      var rawUris = trimmedSrcset.split(pattern);

      // for each tuples
      var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
      for (var i = 0; i < nbrUrisWith2parts; i++) {
        var innerIdx = i * 2;
        // sanitize the uri
        result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
        // add the descriptor
        result += (" " + trim(rawUris[innerIdx + 1]));
      }

      // split the last item into uri and descriptor
      var lastTuple = trim(rawUris[i * 2]).split(/\s/);

      // sanitize the last uri
      result += $$sanitizeUri(trim(lastTuple[0]), true);

      // and add the last descriptor if any
      if (lastTuple.length === 2) {
        result += (" " + trim(lastTuple[1]));
      }
      this[key] = value = result;
    }

    if (writeAttr !== false) {
      if (value === null || isUndefined(value)) {
        this.$$element.removeAttr(attrName);
      } else {
        this.$$element.attr(attrName, value);
      }
    }

    // fire observers
    // 执行监控回调
    var $$observers = this.$$observers;
    $$observers && forEach($$observers[observer], function(fn) {
      try {
        fn(value);
      } catch (e) {
        $exceptionHandler(e);
      }
    });
  },


  /**
   * 监控属性中的key
   */
  $observe: function(key, fn) {
    var attrs = this,
        $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
        listeners = ($$observers[key] || ($$observers[key] = []));

    listeners.push(fn);
    // 初始的时候执行一次
    $rootScope.$evalAsync(function() {
      if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
        // no one registered attribute interpolation function, so lets call it manually
        fn(attrs[key]);
      }
    });

    return function() {
      arrayRemove(listeners, fn);
    };
  }
};

在看核心编译compile函数:

// 核心编译
function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  if (!($compileNodes instanceof jqLite)) {
    // jquery always rewraps, whereas we need to preserve the original selector so that we can
    // modify it.
    $compileNodes = jqLite($compileNodes);
  }

  forEach($compileNodes, function(node, index) {
    // 如果说要编译的节点中有纯文本 则用span包裹
    // 因为不能编译顶级的文本节点,因为文本节点不能附加scope data
    if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
      $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
    }
  });
  // 节点中所有的linkFn的复合link函数compositeLinkFn
  var compositeLinkFn =
          compileNodes($compileNodes, transcludeFn, $compileNodes,
                       maxPriority, ignoreDirective, previousCompileContext);
  compile.$$addScopeClass($compileNodes);
  var namespace = null;
  return function publicLinkFn(scope, cloneConnectFn, options) {
    // 省略
  };
}

可以看出先调用compileNodes(收集$compileNodes元素中所有的link函数)得到compositeLinkFn,他会在publicLinkFn函数中会被调用,具体看下边关于publicLinkFn的分析。

compileNodes

在看publicLinkFn的逻辑之前很有必要看看compileNodes到底是怎样收集指令得到所有的link函数的,看具体代码:

/**
 * 真正的编译所有节点
 */
function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective, previousCompileContext) {
  var linkFns = [], // 所有的link函数
      attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;

  for (var i = 0; i < nodeList.length; i++) {
    // 为每一个节点创建属性实例
    // 一一对应
    attrs = new Attributes();

    // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
    // 收集指令
    directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
                                    ignoreDirective);

    // 应用指令 得到当前节点的link 函数
    nodeLinkFn = (directives.length)
        ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
                                  null, [], [], previousCompileContext)
        : null;

    if (nodeLinkFn && nodeLinkFn.scope) {
      compile.$$addScopeClass(attrs.$$element);
    }
    // 递归得到其子节点的link函数(当然也是一compositeLinkFn)
    // 这里可以看到如果说在当前节点的指令中有terminal的指令的话 一样会认为不必再去编译其子节点的
    childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
                  !(childNodes = nodeList[i].childNodes) ||
                  !childNodes.length)
        ? null
        : compileNodes(childNodes,
             nodeLinkFn ? (
              (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
                 && nodeLinkFn.transclude) : transcludeFn);

    if (nodeLinkFn || childLinkFn) {
      linkFns.push(i, nodeLinkFn, childLinkFn);
      linkFnFound = true;
      nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
    }

    //use the previous context only for the first element in the virtual group
    previousCompileContext = null;
  }

  // return a linking function if we have found anything, null otherwise
  // 返回一个link函数,可以统一调用所有的linkFns
  return linkFnFound ? compositeLinkFn : null;

  function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
    // 省略
  }
}

基本过程就是利用collectDirectives收集完指令,下一步通过applyDirectivesToNode来根据指令去更新元素节点且返回相应的link函数。有关键的两个函数:collectDirectivesapplyDirectivesToNode

首先,来看collectDirectives,故名思议是纯粹的收集当前节点上到底有哪些指令的:

function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  var nodeType = node.nodeType,
      attrsMap = attrs.$attr,
      match,
      className;
  // 参数中的 directives 就是结果集
  // 判断元素 文本 和 注释
  switch (nodeType) {
    case NODE_TYPE_ELEMENT: /* Element */
      // use the node name: <directive>
      // nodeName指令
      // 增加指令
      // addDirective的分析紧挨着collectDirectives之后
      addDirective(directives,
          directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);

      // iterate over the attributes
      // 同时还得遍历其属性,看看有没有可用的指令
      for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
               j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
        var attrStartName = false;
        var attrEndName = false;

        attr = nAttrs[j];
        name = attr.name;
        value = trim(attr.value);

        // support ngAttr attribute binding
        ngAttrName = directiveNormalize(name);
        if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
          name = name.replace(PREFIX_REGEXP, '')
            .substr(8).replace(/_(.)/g, function(match, letter) {
              return letter.toUpperCase();
            });
        }

        // 注意start 和  end
        // 会被替换掉
        // 这时候ng会认为可能是跨越多个元素的指令
        // 李例如 ng-repeat-start 和 ng-repeat-end
        var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
        if (directiveIsMultiElement(directiveNName)) {
          if (ngAttrName === directiveNName + 'Start') {
            attrStartName = name;
            attrEndName = name.substr(0, name.length - 5) + 'end';
            name = name.substr(0, name.length - 6);
          }
        }

        nName = directiveNormalize(name.toLowerCase());
        attrsMap[nName] = name;
        if (isNgAttr || !attrs.hasOwnProperty(nName)) {
            attrs[nName] = value;
            if (getBooleanAttrName(node, nName)) {
              attrs[nName] = true; // presence means true
            }
        }
        // 如果有属性插值指令的话 也增加
        // addAttrInterpolateDirective的分析紧挨着上边所说的addDirective之后
        addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
        addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
                      attrEndName);
      }

      // class指令
      className = node.className;
      if (isObject(className)) {
          // Maybe SVGAnimatedString
          className = className.animVal;
      }
      if (isString(className) && className !== '') {
        while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
          nName = directiveNormalize(match[2]);
          if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
            attrs[nName] = trim(match[3]);
          }
          className = className.substr(match.index + match[0].length);
        }
      }
      break;
    case NODE_TYPE_TEXT: /* Text Node */
      if (msie === 11) {
        // Workaround for #11781
        while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
          node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
          node.parentNode.removeChild(node.nextSibling);
        }
      }
      // 纯文本,只能是一种情况,算是指令的东西:插值表达式
      // 具体代码分析在紧挨着addAttrInterpolateDirective之后
      addTextInterpolateDirective(directives, node.nodeValue);
      break;
    case NODE_TYPE_COMMENT: /* Comment */
      try {
        match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
        if (match) {
          nName = directiveNormalize(match[1]);
          // 注释级别的 也会增加
          if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
            attrs[nName] = trim(match[2]);
          }
        }
      } catch (e) {
        // turns out that under some circumstances IE9 throws errors when one attempts to read
        // comment's node value.
        // Just ignore it and continue. (Can't seem to reproduce in test case.)
      }
      break;
  }
  // 按照优先级排序(优先级大的在起始位置)
  // 以便直接按该顺序直接执行
  directives.sort(byPriority);
  return directives;
}
给目标指令数组tDirectives增加指令
function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName, endAttrName) {
  if (name === ignoreDirective) return null;
  var match = null;
  if (hasDirectives.hasOwnProperty(name)) {//存在该指令
    // 执行directivefactory得到指令配置集合 依旧是取得xxxDirective 
    // 因为在创建指令的`directive`函数中创建了访问directiveFactory的service
    // 而这个service的key就是指令名+Directive
    for (var directive, directives = $injector.get(name + Suffix),
        i = 0, ii = directives.length; i < ii; i++) {
      try {
        directive = directives[i];
        if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
             directive.restrict.indexOf(location) != -1) {
          // 达到条件了才会加入到tDirectives中
          if (startAttrName) {
            // 跨越多个元素的指令 也就是 有start还有end的 例如 ng-repeat
            directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
          }
          tDirectives.push(directive);
          match = directive;
        }
      } catch (e) { $exceptionHandler(e); }
    }
  }
  return match;
}
// 增加属性中有插值表达式“指令” 专门处理插值表达式
function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  var trustedContext = getTrustedContext(node, name);
  allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;

  // 利用插值$interpolate服务得到求插值函数
  // 具体细节暂不追究 之后文章中会有相关分析
  var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);

  // 不带有插值 返回就行了
  if (!interpolateFn) return;

  if (name === "multiple" && nodeName_(node) === "select") {
    throw $compileMinErr("selmulti",
        "Binding to the 'multiple' attribute is not supported. Element: {0}",
        startingTag(node));
  }

  // 增加 “插值” 伪指令
  // 可以把插值理解为一个特殊的指令就好,只是表示方法不一样
  directives.push({
    priority: 100,
    compile: function() {
        return {
          pre: function attrInterpolatePreLinkFn(scope, element, attr) {
            var $$observers = (attr.$$observers || (attr.$$observers = createMap()));

            if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
              throw $compileMinErr('nodomevents',
                  "Interpolations for HTML DOM event attributes are disallowed.  Please use the " +
                      "ng- versions (such as ng-click instead of onclick) instead.");
            }

            // If the attribute has changed since last $interpolate()ed
            var newValue = attr[name];
            if (newValue !== value) {
              // we need to interpolate again since the attribute value has been updated
              // (e.g. by another directive's compile function)
              // ensure unset/empty values make interpolateFn falsy
              interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
              value = newValue;
            }

            // if attribute was updated so that there is no interpolation going on we don't want to
            // register any observers
            if (!interpolateFn) return;

            // initialize attr object so that it's ready in case we need the value for isolate
            // scope initialization, otherwise the value would not be available from isolate
            // directive's linking fn during linking phase
            // 执行插值函数 得到新的值
            attr[name] = interpolateFn(scope);

            ($$observers[name] || ($$observers[name] = [])).$$inter = true;
            // 增加watch 如果发生变化了 那么就更新对应的属性值 
            (attr.$$observers && attr.$$observers[name].$$scope || scope).
              $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
                //special case for class attribute addition + removal
                //so that class changes can tap into the animation
                //hooks provided by the $animate service. Be sure to
                //skip animations when the first digest occurs (when
                //both the new and the old values are the same) since
                //the CSS classes are the non-interpolated values
                if (name === 'class' && newValue != oldValue) {
                  attr.$updateClass(newValue, oldValue);
                } else {
                  attr.$set(name, newValue);
                }
              });
          }
        };
      }
  });
}
// 增加纯文本内容中有插值表达式“指令” 专门处理插值表达式
function addTextInterpolateDirective(directives, text) {
  var interpolateFn = $interpolate(text, true);
  if (interpolateFn) {
    // 纯文本插值
    directives.push({
      priority: 0,
      compile: function textInterpolateCompileFn(templateNode) {
        var templateNodeParent = templateNode.parent(),
            hasCompileParent = !!templateNodeParent.length;

        // When transcluding a template that has bindings in the root
        // we don't have a parent and thus need to add the class during linking fn.
        if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);

        return function textInterpolateLinkFn(scope, node) {
          var parent = node.parent();
          if (!hasCompileParent) compile.$$addBindingClass(parent);
          compile.$$addBindingInfo(parent, interpolateFn.expressions);
          scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
            // 是文本节点 所以设置更新的话要用nodeValue
            node[0].nodeValue = value;
          });
        };
      }
    });
  }
}
function byPriority(a, b) {
  var diff = b.priority - a.priority;
  if (diff !== 0) return diff;
  if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  return a.index - b.index;
}

整个collectDirectives的代码还是比较多的,基本过程就是判断当前节点是否是元素指令、属性指令、class指令、注释指令以及特殊的“插值表达式”(在属性中以及纯文本中的插值表达式分别处理),然后把找到的指令依次加入到目标收集指令的数组中。

有了收集的指令集合,然后传入下边要分析的applyDirectivesToNode中,完成根据指令配置更新节点内容以及返回对应的link函数:

代码比较长,不必追究细节的可以看下边(基本上本篇最后的位置了)关于这个函数执行逻辑的一些总结

function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection, originalReplaceDirective, preLinkFns, postLinkFns, previousCompileContext) {

  previousCompileContext = previousCompileContext || {};

  var terminalPriority = -Number.MAX_VALUE,
      newScopeDirective = previousCompileContext.newScopeDirective,
      controllerDirectives = previousCompileContext.controllerDirectives,
      newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
      templateDirective = previousCompileContext.templateDirective,
      nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
      hasTranscludeDirective = false,
      hasTemplate = false,
      hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
      $compileNode = templateAttrs.$$element = jqLite(compileNode),
      directive,
      directiveName,
      $template,
      replaceDirective = originalReplaceDirective,
      childTranscludeFn = transcludeFn,//变换函数
      linkFn,
      directiveValue;

  // executes all directives on the current element
  // 所有的directives都已经是按照优先级排过序的了
  for (var i = 0, ii = directives.length; i < ii; i++) {
    directive = directives[i];
    var attrStart = directive.$$start;
    var attrEnd = directive.$$end;

    // 重新得到跨越多个节点的node集合
    if (attrStart) {
      $compileNode = groupScan(compileNode, attrStart, attrEnd);
    }
    $template = undefined;

    if (terminalPriority > directive.priority) {
      break; // prevent further processing of directives
    }

    if (directiveValue = directive.scope) {
      // 有新scope指令 可以为true也可以是对象 总之 就是要创建
      // 新的scope
      // skip the check for directives with async templates, we'll check the derived sync
      // directive when the template arrives
      if (!directive.templateUrl) {
        if (isObject(directiveValue)) {
          // This directive is trying to add an isolated scope.
          // Check that there is no scope of any kind already
          assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
                            directive, $compileNode);
          // 新的独立scope指令
          newIsolateScopeDirective = directive;
        } else {
          // This directive is trying to add a child scope.
          // Check that there is no isolated scope already
          assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
                            $compileNode);
        }
      }
      // 新的sccope指令
      newScopeDirective = newScopeDirective || directive;
    }

    directiveName = directive.name;

    if (!directive.templateUrl && directive.controller) {
      // 带有templateUrl的需要在后边特殊处理
      // 这里在controllerDirectives中记录哪些指令是有controller的
      // 在nodeLinkFn的逻辑中会用到 具体看后边关于这部分的分析
      directiveValue = directive.controller;
      controllerDirectives = controllerDirectives || createMap();
      assertNoDuplicate("'" + directiveName + "' controller",
          controllerDirectives[directiveName], directive, $compileNode);
      controllerDirectives[directiveName] = directive;
    }

    if (directiveValue = directive.transclude) {
      hasTranscludeDirective = true;
      // 有transclude变换的指令
      // 内部使用的$$tlb配置参数 只有ngIf和ngRepeat用
      // 主要是为了解决在link后还是会增加或替换transcluded节点
      if (!directive.$$tlb) {
        assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
        nonTlbTranscludeDirective = directive;
      }

      if (directiveValue == 'element') {
        // 包括当前元素自身也会被包含在内
        hasElementTranscludeDirective = true;
        terminalPriority = directive.priority;
        $template = $compileNode;
        // 变为注释节点
        $compileNode = templateAttrs.$$element =
            jqLite(document.createComment(' ' + directiveName + ': ' +
                                          templateAttrs[directiveName] + ' '));
        compileNode = $compileNode[0];
        // 把当前节点替换了
        replaceWith(jqCollection, sliceArgs($template), compileNode);
        // 既然需要transclude,那么就需要把这部分内容重新编译了
        // 得到childTranscludeFn以备nodeLinkFn使用
        // 这里可以看出transclude的原理就是把之前的内容compile掉 得到的publiclink函数
        childTranscludeFn = compile($template, transcludeFn, terminalPriority,
                                    replaceDirective && replaceDirective.name, {
                                      // Don't pass in:
                                      // - controllerDirectives - otherwise we'll create duplicates controllers
                                      // - newIsolateScopeDirective or templateDirective - combining templates with
                                      //   element transclusion doesn't make sense.
                                      //
                                      // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
                                      // on the same element more than once.
                                      nonTlbTranscludeDirective: nonTlbTranscludeDirective
                                    });
      } else {
        // 只处理子节点
        $template = jqLite(jqLiteClone(compileNode)).contents();
        $compileNode.empty(); // clear contents
        childTranscludeFn = compile($template, transcludeFn);
      }
    }

    if (directive.template) {
      // 直接就有模板
      hasTemplate = true;
      assertNoDuplicate('template', templateDirective, directive, $compileNode);
      templateDirective = directive;

      // 得到模板内容
      directiveValue = (isFunction(directive.template))
          ? directive.template($compileNode, templateAttrs)
          : directive.template;

      directiveValue = denormalizeTemplate(directiveValue);

      if (directive.replace) {
        replaceDirective = directive;
        if (jqLiteIsTextNode(directiveValue)) {
          $template = [];
        } else {
          $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
        }
        compileNode = $template[0];

        if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
          throw $compileMinErr('tplrt',
              "Template for directive '{0}' must have exactly one root element. {1}",
              directiveName, '');
        }
        // 要用模板替换掉当前节点
        replaceWith(jqCollection, $compileNode, compileNode);

        var newTemplateAttrs = {$attr: {}};

        // combine directives from the original node and from the template:
        // - take the array of directives for this element
        // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
        // - collect directives from the template and sort them by priority
        // - combine directives as: processed + template + unprocessed
        // 
        // 收集模板上的指令
        var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
        // 余下的指令 目的就是为了在下边concat的时候保证指令们顺序
        var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));

        if (newIsolateScopeDirective) {
          // 如果还是对scope的指令
          markDirectivesAsIsolate(templateDirectives);
        }
        // 合并模板上指令到directives中
        directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
        // 当然也要把属性给合并到一起
        mergeTemplateAttributes(templateAttrs, newTemplateAttrs);

        ii = directives.length;
      } else {
        // 直接赋HTML就可以
        $compileNode.html(directiveValue);
      }
    }

    if (directive.templateUrl) {
      hasTemplate = true;
      assertNoDuplicate('template', templateDirective, directive, $compileNode);
      templateDirective = directive;

      if (directive.replace) {
        replaceDirective = directive;
      }

      // 有模板 但是是一个url 需要请求模板内容
      // 因为compileTemplateUrl是异步的
      // 所以这里需要把当前上下文的依赖参数都传过去
      nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
          templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
            controllerDirectives: controllerDirectives,
            newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
            newIsolateScopeDirective: newIsolateScopeDirective,
            templateDirective: templateDirective,
            nonTlbTranscludeDirective: nonTlbTranscludeDirective
          });
      ii = directives.length;
    } else if (directive.compile) {
      try {
        // 直接调用directive的compile
        linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
        if (isFunction(linkFn)) {
          addLinkFns(null, linkFn, attrStart, attrEnd);
        } else if (linkFn) {
          addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
        }
      } catch (e) {
        $exceptionHandler(e, startingTag($compileNode));
      }
    }

    if (directive.terminal) {
      // 终止 最后
      nodeLinkFn.terminal = true;
      terminalPriority = Math.max(terminalPriority, directive.priority);
    }

  }

  // 指令
  nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  nodeLinkFn.templateOnThisElement = hasTemplate;
  nodeLinkFn.transclude = childTranscludeFn;

  previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;

  // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  return nodeLinkFn;

  ////////////////////

  // 记录增加所有的link函数
  function addLinkFns(pre, post, attrStart, attrEnd) {
    if (pre) {
      if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
      pre.require = directive.require;
      pre.directiveName = directiveName;
      if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
        pre = cloneAndAnnotateFn(pre, {isolateScope: true});
      }
      preLinkFns.push(pre);
    }
    if (post) {
      if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
      post.require = directive.require;
      post.directiveName = directiveName;
      if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
        post = cloneAndAnnotateFn(post, {isolateScope: true});
      }
      postLinkFns.push(post);
    }
  }

  // 返回的 nodeLinkFn
  function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn, thisLinkFn) {
    // 省略
  }
}

上边需要注意的一个是compileTemplateUrl这个函数,也就是处理带有模板url的情况,看下代码:

// 编译请求模板
function compileTemplateUrl(directives, $compileNode, tAttrs, $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  var linkQueue = [],
      afterTemplateNodeLinkFn,
      afterTemplateChildLinkFn,
      beforeTemplateCompileNode = $compileNode[0],
      origAsyncDirective = directives.shift(),
      derivedSyncDirective = inherit(origAsyncDirective, {
        templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
      }),
      templateUrl = (isFunction(origAsyncDirective.templateUrl))
          ? origAsyncDirective.templateUrl($compileNode, tAttrs)
          : origAsyncDirective.templateUrl,
      templateNamespace = origAsyncDirective.templateNamespace;

  $compileNode.empty();

  $templateRequest(templateUrl)
    .then(function(content) {
      var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;

      content = denormalizeTemplate(content);

      if (origAsyncDirective.replace) {
        if (jqLiteIsTextNode(content)) {
          $template = [];
        } else {
          $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
        }
        compileNode = $template[0];

        if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
          throw $compileMinErr('tplrt',
              "Template for directive '{0}' must have exactly one root element. {1}",
              origAsyncDirective.name, templateUrl);
        }

        // 依旧是替换 这部分和applyDirectivesToNode中的
        // directive.template逻辑基本相同 因为依旧拿到了模板内容了
        // 就当做字符串处理了
        tempTemplateAttrs = {$attr: {}};
        replaceWith($rootElement, $compileNode, compileNode);
        // 一样 收集指令
        var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);

        if (isObject(origAsyncDirective.scope)) {
          markDirectivesAsIsolate(templateDirectives);
        }
        directives = templateDirectives.concat(directives);
        mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
      } else {
        compileNode = beforeTemplateCompileNode;
        $compileNode.html(content);
      }

      directives.unshift(derivedSyncDirective);

      // 其实是已经递归去调用applyDirectivesToNode了
      afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
          childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
          previousCompileContext);
      forEach($rootElement, function(node, i) {
        if (node == compileNode) {
          $rootElement[i] = $compileNode[0];
        }
      });
      afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);

      while (linkQueue.length) {
        // 如果说delayedNodeLinkFn先调用了 那么此时需要在这里
        // 执行真正的linkFn
      }
      linkQueue = null;
    });
  
  // 返回的是延迟的nodeLinkFn
  return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
    // 省略
  };
}

可以看出的是需要请求得到templateUrl的内容,然后做了类似于对template类似的处理逻辑,最后返回delayedNodeLinkFn

这里总结下applyDirectivesToNode(比较代码实在是太长了),他处理的东西主要是收集得到的指令集合做循环(除非遇到了terminal的指令,否则循环完),主要处理:

  • 判断指令是否是创建新的Scope以及是否是独立Scope,然后用变量保存

  • 收集带有controller的指令记录下来

  • 做transclude处理

  • 有template或者templateUrl特殊处理

  • 调用指令的compile函数,根据返回值保存对应的pre或者post的link函数

结语

到这里呢,基本上关于compile部分的基本完了,其实代码中还有关于link的逻辑大部分是省略了的,篇幅有限,就留到下篇继续分析。整个过程还是比较复杂的,有人利用实例做了一张compile的过程图:

compile图

发布于: 2015年 10月 23日