【问题标题】:Angularjs $compile input html or elementAngularjs $compile 输入 html 或元素
【发布时间】:2013-12-12 08:41:18
【问题描述】:

我正在阅读“使用 AngularJS 掌握 Web 应用程序开发”一书,并在第 220 页遇到了以下代码:

var element = $compile('<button size="large"></button>')($rootScope)

但是,根据位于http://docs.angularjs.org/guide/compiler 的文档,$compile 函数需要一个 angular.element(包装的 html)输入。

纯 html 和 angular 元素是否都是 $compile 函数的有效输入(或者这些文档之一不正确)?

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

如有疑问 - go to the source

这永远是最好的选择

  if (!($compileNodes instanceof jqLite)) {
    // jquery always rewraps, whereas we need to preserve the original selector so that we can
    // modify it.
    $compileNodes = jqLite($compileNodes);
  }

因此,如果它传递的不是 jqLit​​e 元素 - 它会将其包装在 jqLit​​e 元素中。

这允许传递内容、jqLit​​e 元素或普通 DOM 元素。

如果您在源代码go to the tests 中找不到您要查找的内容。

在这里你可以在第 88 行看到$compileing HTML text

 element = $compile('<div></div>')($rootScope);

这里可以看到$compileing a jqLite element

element = jqLite('<div>{{1+2}}</div>');
$compile(element)($rootScope);

如果您在规范中没有找到 go to docs

嗯?那不是文档!那是源头,你骗我的!

根据我的经验,Angular 在源代码中的记录比在在线文档中好多。该文档是最新的,并且所有类型和用法都存在。那里要简单得多:

  • @param {string|DOMElement} element 要编译成模板函数的元素或 HTML 字符串。

虽然在这种情况下docs.angularjs 也做得不错,但导航时间更长。

仍然没有 - 你可以查看DefinitelyTyped

这是 TypeScript 的一堆类型定义。它很有用,因为它可以很好地告诉您 - 类型 :)

 interface ICompileService {
        (element: string, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction;
        (element: Element, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction;
        (element: JQuery, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction;
    }

如您所见 - 这是我们在其他地方找到的三个选项。一个字符串、一个 Element 或一个 JQuery(通常是精简版)实例。

【讨论】:

  • @AlexanderMarquardt 很高兴我能帮上忙
猜你喜欢
  • 1970-01-01
  • 2019-03-13
  • 2018-09-15
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-06
  • 2020-09-20
相关资源
最近更新 更多