Mastering Web Application

(Rick Simeone) #1
Chapter 9
childElement.remove();
childScope.$destroy();
childElement = undefined;
childScope = undefined;
}
if (newValue) {
childScope = scope.$new();
childElement = transclude(childScope, function(clone){
element.after(clone);
});
}
});

The directive transcludes the entire element (transclude: 'element'). We provide
a compile function, which gives us access to the transclusion function, which returns
the link function, where we $watch the if attribute expression.


We use $watch rather than $observe here because the if attribute
should contain an expression to be evaluated rather than a string to
be interpolated.

When the expression changes, we tidy up the scope and child element, if they exist.
This is important to ensure that we don't have any memory leaks. If the expression
evaluates to true, we create a new child scope and then use it with the transclusion
function to clone a new copy of the transcluded elements. We insert these elements
after the element that contained the directive.


Using the priority property in a directive

All directives have a priority, defaulting to zero, as in the case of the alert directive.
On each element, AngularJS compiles the higher priority directives before lower
priority ones. We can specify this using the priority property on the directive
definition object.


If a directive has transclude: 'element', the compiler will only transclude
attributes whose directives have a lower priority than the current directive, in
other words, the element's directives that have not yet been processed.

Free download pdf