Reputation: 1539
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
Reputation: 276286
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.
Here you can see it $compile
ing HTML text in line 88:
element = $compile('<div></div>')($rootScope);
Here you can see it $compile
ing a jqLite element
element = jqLite('<div>{{1+2}}</div>');
$compile(element)($rootScope);
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.
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