Angularjs $编译输入html或元素

Ale*_*rdt 1 javascript angularjs

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

var element = $compile('<button size="large"></button>')($rootScope)
Run Code Online (Sandbox Code Playgroud)

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

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

Ben*_*aum 8

如果有疑问 - 去源头.

这总是最好的选择

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

因此,如果它传递的只是一个jqLit​​e元素 - 它将它包装在一个jqLit​​e元素中.

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

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

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

 element = $compile('<div></div>')($rootScope);
Run Code Online (Sandbox Code Playgroud)

在这里你可以看到它$compile的jqLit​​e元素

element = jqLite('<div>{{1+2}}</div>');
$compile(element)($rootScope);
Run Code Online (Sandbox Code Playgroud)

如果你没有在规范中找到文档.

咦?那不是文档!那是源头,你欺骗了我!

根据我的经验角被很多更好地记录在源代码比在线文档.文档更新,所有类型和用法都存在.那里更简单:

  • @param {string | DOMElement}元素要编译成模板函数的元素或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;
    }
Run Code Online (Sandbox Code Playgroud)

如您所见 - 这些是我们在其他地方找到的三个选项.字符串,Element或JQuery(通常是lite)实例.