在AngularJS中,如何删除使用$ compile创建的元素?

Kay*_*ast 10 angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

我写了一个简单的例子,我使用$ compile动态创建一个元素.这个新元素有另一个按钮,我想要删除这个元素(我已经读过,破坏范围/元素以避免泄漏是很好的).但函数closeThisElement()不起作用; 请帮忙.

请参阅此处的plunker:http://plnkr.co/edit/js7mpUMndjZEdMvRMuZk?p = preview

同时复制以下部分代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

Zac*_*yle 10

他们必须在美元范围内.目前,它们只是您的链接可用的功能,但不在html中.试试这个.

$scope.closeThisElement = closeThisElement;
Run Code Online (Sandbox Code Playgroud)

要仅消除已编译的组件,请保存实例并使用它.

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;
}
Run Code Online (Sandbox Code Playgroud)

值得一提的是,您可以使用ng-show或ng-hide而不是创建和删除新元素,而不必编译它.