Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs $transclude - How to access the html content of clone object?

I am trying to acccess the content of the 'clone' object inside of a $transclude function in a directive, but clone.html() returns undefined. How do I access the html content of the directive element / clone ?

.directive('somedirective', function(){
    return {
        restrict: 'EA'
        , replace: true
        , transclude: true
        , scope: true
         , controller: function ($scope, $element, $transclude, $log) {
             $transclude(function (clone) {
                 console.log(clone.html()); //undefined??
                 console.log(clone.text()); //works but strips the html tags
                 // How do I access the html content of clone???
                })
             }
         }

SEE PLUNKER

like image 907
Jarnal Avatar asked Dec 02 '25 07:12

Jarnal


1 Answers

You were getting undefined because your clone is actually three elements, text-div-text. So, removing the whitespace between <drt> and <div> fixes part of the problem, so "clone.html()" will then print "testing". The second part of the problem, is that .html() uses the "innerHTML" property, so it won't include the root DOM element of clone. Instead, try using clone[0].outerHTML or angular.element("<div/>").append(clone).html().

http://plnkr.co/edit/mOnlFLJMHkQ0iQIeZTwd?p=preview

controller: function($scope, $element, $transclude, $log){
 $transclude(function(clone) {
     console.log(clone[0].innerHTML); //undefined??
     console.log(clone[0].outerHTML); //undefined??
     console.log(angular.element("<div/>").append(clone).html()); //undefined??
     console.log(clone.text()); //works but strips the html tags    
  });
like image 85
Craig Squire Avatar answered Dec 03 '25 21:12

Craig Squire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!