Alexander Marquardt
Alexander Marquardt

Reputation: 1539

Angularjs $compile input html or element

I am reading through the book "Mastering Web Application Development with AngularJS" and have come across the following code on page 220:

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

However, according to the documentation located at: http://docs.angularjs.org/guide/compiler, the $compile function expects an angular.element (wrapped html) input.

Are pure html as well as an angular element both valid inputs to the $compile function (or is one of these documents incorrect)?

Upvotes: 1

Views: 1379

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276286

When in doubt - go to the source.

That's always the best option

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

So if it's passed anything but a jqLite element - it wraps it in a jqLite element.

This allows passing content, a jqLite element, or a normal DOM element.

If you don't find what you're looking for in the source go to the tests.

Here you can see it $compileing HTML text in line 88:

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

Here you can see it $compileing a jqLite element

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

If you don't find that in the spec go to docs.

Huh? That's not the docs! That's the source, you tricked me!

In my experience Angular is much better documented in the source code than in the online docs. The documentation is more up to date and all the types and usages are present. It's a lot simpler there:

  • @param {string|DOMElement} element Element or HTML string to compile into a template function.

Although in this case docs.angularjs also does a decent job, it's just longer to navigate.

Still not there - you can check out DefinitelyTyped.

That's a bunch of type definitions for TypeScript. It's useful since it tells you well - the types :)

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

As you can see - these are the three options like we found elsewhere. A string, an Element or a JQuery (lite usually) instance.

Upvotes: 8

Related Questions