Angularjs$编译输入html或元素

Angularjs $compile input html or element

本文关键字:元素 html 输入 编译 Angularjs      更新时间:2023-09-26

我正在阅读《使用AngularJS掌握Web应用程序开发》一书,在第220页上看到了以下代码:

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

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

纯html和angular元素都是$compile函数的有效输入吗(或者其中一个文档不正确)?

如果有疑问,请转到源代码

这总是的最佳选择

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

因此,如果它传递了除jqLite元素之外的任何东西,它就会将其封装在jqLite元件中。

这允许传递内容、jqLite元素或普通DOM元素。

如果您在源代码中找不到您要查找的内容,请进行测试

在这里,您可以在第88行中看到$compileingHTML文本:

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

在这里你可以看到它$compile通过jqLite元素

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

如果您在规范中找不到,请转到文档

嗯?那不是医生!这就是消息来源,你骗了我!

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

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

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

仍然不在那里-你可以查看绝对类型

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

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

正如你所看到的,这是我们在其他地方找到的三种选择。字符串、元素或JQuery(通常为lite)实例。