Let's say that we want to create a new DOM element called <my:greeter/>
that displays a greeting.
We want this HTML source:
<div ng:init="salutation='Hello'; name='World'"> <my:greeter salutation="salutation" name="name"/> </div>
to produce this DOM:
<div ng:init="salutation='Hello'; name='World'"> <my:greeter salutation="salutation" name="name"/> <span class="salutation">Hello</span> <span class="name">World</span>! </my:greeter> </div>
That is, the new <my:greeter/>
tag's salutation
and name
attributes should be transformed by
the compiler such that two <span>
tags display the values of the attributes, with CSS classes
applied to the output.
The following code snippet shows how to write a following widget definition that will be processed
by the compiler. Note that you have to declare the namespace my
in
the page:
angular.widget('my:greeter', function(compileElement){ var compiler = this; compileElement.css('display', 'block'); var salutationExp = compileElement.attr('salutation'); var nameExp = compileElement.attr('name'); return function(linkElement){ var salutationSpan = angular.element('<span class="salutation"></span'); var nameSpan = angular.element('<span class="name"></span>'); linkElement.append(salutationSpan); linkElement.append(compiler.text(' ')); linkElement.append(nameSpan); linkElement.append(compiler.text('!')); this.$watch(salutationExp, function(value){ salutationSpan.text(value); }); this.$watch(nameExp, function(value){ nameSpan.text(value); }); }; });
Note: For more about widgets, see Understanding Angular Widgets
and the widget API reference page
.
<my:greeter>
Here are the steps that the compiler takes in processing the page that contains the widget definition above: