In AngularJS, how can I remove an element created using $compile?

angularjs, angularjs-directive, angularjs-ng-repeat, angularjs-scope

Solution

They have to be on the $scope. Currently they are just functions available to your link, but not within the html. Try this.

$scope.closeThisElement = closeThisElement;

To eliminate only the compiled component, save the instance and use that.

link: function($scope, $element) {
    var newElement;
    function closeThisElement(){
        newElement.remove();
    }
    function addComment(){
        newElement = $compile('<div class="publishComment"><input type="text" ng-model="contentForReply"/><button ng-click="publishReply(contentForReply); closeThisElement()">Publish Reply</button></div>')($scope);
        $element.append(newElement);
    }
    $scope.addComment = addComment;
    $scope.closeThisElement = closeThisElement;
}

It might be worth mentioning, that rather than creating and removing a new element, you could use ng-show or ng-hide and never have to compile it.

Problem

I've written a simple example, where I create an element dynamically using $compile. This new element has another button, with which I want to remove this element (I've read that it is good to destroy scope/elements to avoid leaks). But the function closeThisElement() is not working; please help. See plunker here: http://plnkr.co/edit/js7mpUMndjZEdMvRMuZk?p=preview Also reproducing part of the code below: ``` link: function($scope, $element) { function closeThisElement(){ $element.remove(); } function addComment(){ $element.append($compile('<div class="publishComment"><input type="text" ng-model="contentForReply"/><button ng-click="publishReply(contentForReply); closeThisElement()">Publish Reply</button></div>')($scope)); } $scope.addComment = addComment; } ```

Original source