L457
L457

Reputation: 1032

How do i select/replace element components by css classes inside a link function?

I have been trying to select and replace a specific element in my directive template which has the class .placeholder. I have tried using replaceWith() but I get an error saying it is not a function. How do I select/replace element components by css classes inside a link function?

Here is my code:

var comments = function($compile){
  return {
    templateUrl : 'modules/comments/commentsDirective.html',
    restrict:'E',
    scope:{
      collection: '='
    },

    link: function(scope, element, attrs){
        if(scope.collection.data.replies){
          var elementResult = element[0].getElementsByClassName('placeholder');
          console.log(elementResult); //works fine 

          //throws an error here:***
          elementResult.replaceWith($compile('<ul ng-repeat="comment in collection.data"><comments collection="comment"></comments></ul>')(scope));

        }
    }
  };
};

Upvotes: 2

Views: 49

Answers (1)

scniro
scniro

Reputation: 16989

To call the jqLite function replaceWith(), we need to wrap our raw selector with angular.element(). Per angular.element docs...

Wraps a raw DOM element or HTML string as a jQuery element.

Observe the following change...

var elementResult =   
    angular.element(element[0].getElementsByClassName('placeholder'));

Upvotes: 1

Related Questions