I'm trying to learn AngularJS and I'm trying to dynamically compile some DOM elements... I've tried the demo:
try {
var templateHTML = angular.element('<p>{{total}}</p>'),
scope = ....;
var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
//attach the clone to DOM document at the right place
});
//now we have reference to the cloned DOM via `clone`
} catch (ex) {
alert(ex.message);
}
but all I get back is a "$compile is not defined"
HELP!
Overview. Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. The compilation is a process of walking the DOM tree and matching DOM elements to directives. Note: This document is an in-depth reference of all directive options.
Solution bindToController : Angular introduces a new property to the directive definition object called bindToController. BindToController enables the inherited properties to be bound to the Controller without $scope object.
Compiler is an AngularJS service which traverses the DOM looking for attributes. The compilation process happens in two phases. Compile: traverse the DOM and collect all of the directives. The result is a linking function. Link: combine the directives with a scope and produce a live view.
AngularJS Directive's link key defines link function for the directive. Precisely, using link function, we can define directive's API & functions that can then be used by directive to preform some business logic. The link function is also responsible for registering DOM listeners as well as updating the DOM.
A sample code for using $compile in a directive. Basically go ahead & first append the element to DOM (might want to keep it invisible), then run the compile by using a finder.. as mentioned by rtcherry, $compile should be injected.
//
componentModule.directive('getCompilerWk', function($compile) {
return {
restrict: 'A',
link: function(scope, elm, attr) {
elm.click(function(){
$(body).append(templateHTML);
$compile($(body).find('p'))(scope);
})
}
};
});
Where are you calling this code from? Is it safe to assume it is outside of the Angular framework by your use of angular.element(...)?
If so, you can use this:
// Split across two lines for readability...
angular.element(<something within Angular's scope>)
.injector().get('$compile')(...)
If not, you may simply need to inject $compile into the controller/directive/service.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With