I'm having trouble getting the compiled html of a page in AngularJS. Here's the code:
JS:
<script src="http://code.angularjs.org/1.2.0rc1/angular.min.js"></script>
<script>
var app = angular.module('main', []);
app.directive("compile", ['$compile', function ($compile) {
return {
link: function(scope, elem, attr){
var compiledHTML = $compile(elem.contents())(scope);
console.log(compiledHTML);
var returnString = '';
for(i=0; i<compiledHTML.length; i++)
returnString += compiledHTML[i].outerHTML;
console.log(returnString);
}
};
}]);
</script>
HTML:
<html ng-app="main" compile>
<body>
{{3 + 4}}
</body>
</html>
What is strange is in the first console.log(), it shows the compiled data, 7, in the outerHTML property, but when I output all the .outerHTML, it shows the uncompiled version, {{3 + 4}}
AngularJS extends HTML with ng-directives. The ng-app directive defines an AngularJS application. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data. The ng-bind directive binds application data to the HTML view.
AngularJS compilation process takes place in the Web Browser. No Server side or pre-compilation step is involved. Angular uses $compiler service to compile your Angular HTML page. The Angular compilation process begins after your HTML page (static DOM) is fully loaded.
Compile function: It is used for template DOM Manipulation and collect all of the directives. Link function: It is used for registering DOM listeners as well as instance DOM manipulation. It is executed once the template has been cloned.
Looks like it was a timing issue. Waiting to process the compiledHTML did the trick.
$timeout(function(){
var returnString = '';
for(i=0; i<compiledHTML.length; i++)
returnString += compiledHTML[i].outerHTML;
console.log(returnString);
},0);
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