7

我寫了一個簡單的例子,我使用$ 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; 
} 

回答

8

他們必須在$範圍。目前它們只是可用於鏈接的功能,但不在html中。嘗試這個。

$scope.closeThisElement = closeThisElement; 

要僅消除已編譯的組件,請保存實例並使用它。

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; 
} 

值得一提的是,不是創建和刪除一個新元素,而是使用ng-show或ng-hide,而不必編譯它。

+0

問題是這將它鏈接到父級的範圍,並且整個父元素被取消。我只想要$ compile創建的元素被刪除。我知道ng-repeat已經是'繼承'範圍,所以設置範圍:true也不應該有任何影響。如果我將範圍與範圍隔離:{},它也不起作用。感謝您查看它。 –

+0

@KayaToast,編輯帖子,希望它有幫助。 –

+0

我用你的更新後的代碼嘗試了它,但是現在沒有元素被刪除。是的,ng-show/hide是一個選項。但我真的想了解範圍並編譯。我已經將這個簡化示例中需要解決的更復雜的問題抽象出來了。 –

0

可以在指令配置使用templatetemplateUrl

app.directive('mydirective', function(){ 
    return { 
     // other configuration 
     restrict: 'E', 
     template: '<div ng-repeat="comment in comments">' + 
         '<div>{{comment.hello}}</div>' + 
         '<button type="button" ng-click="removeComment(comment)"></button>' + 
        '</div>', 
     link: function(scope, element, attrs){ 
      scope.comments = [{ hello: 'bonjour' }, { hello: 'konichiva' }]; 

      scope.removeComment = function(comment){ 
       scope.comments.splice(scope.comments.indexOf(comment), 1); 
      } 
     } 
    }; 
}); 
+0

感謝您的替代方法。但我真的想了解如何範圍和編譯工作。我想明白,具體來說,我該如何刪除嵌套在ng-repeat中的編譯元素。 –

+0

@KayaToast編譯元素是轉換爲jQuery元素的實際字符串。這並不是很好的做法 – karaxuna

+0

似乎很奇怪,如果這確實是AngularJS的方式。比方說,如果我在ng-repeat中有100個項目,並且在該模板中,有2個鏈接可以創建指令,那麼我需要預先填充200個元素。如果他們進一步嵌套,那麼更是如此。和他們每個人都有關聯的範圍等。似乎相當低效。 –

1

功能closeThisElement需要是$範圍的一部分,它在你的HTML評價:

$scope.closeThisElement = closeThisElement;

雖然,Angular的鏈接函數中的$element指向指令元素本身。

$element.remove()將從DOM中刪除指令。您可以使用angular.element()(jQuery lite的別名)來查找附加內容並刪除它以保留tk-listview元素。

相關問題