Skip to content Skip to sidebar Skip to footer

Remove HTML Element On Click In Angular Js

This is my Directive. which display one Div on the body. app.directive('autosuggest', function($rootScope) { return { scope: { doneFlag : '=',

Solution 1:

Use below in your directive.

Directive

app.directive("removeMe", function() {
      return {
            link:function(scope,element,attrs)
            {
                element.bind("click",function() {
                    element.remove();
                });
            }
      }

});

HTML

<div class="showw" remove-me>
   <img id="hideDivOnClick" src="ddd.png"/>
</div>

Working Demo


Solution 2:

You can simply create a directive, that adds a function that will remove the html of the element. Then you can just stick it on an ng-click. I made a fiddle here: http://jsfiddle.net/qDhT9/

// in the directive
scope.remove = function() {
    elt.html('');
};
// in the dom
<div remove-on-click ng-click="remove()"> 
    REMOVE ME 
</div>

Hope this helped!


Solution 3:

For clearing/removing html elements, we can use the following methods

var myEl = angular.element( document.querySelector( '#divID' ) );
myEl.empty();  //clears contents

var myEl = angular.element( document.querySelector( '#divID' ) );
myEl.remove();   //removes element

Reference : http://blog.sodhanalibrary.com/2014/08/empty-or-remove-element-using-angularjs.html#.Vd0_6vmqqkp


Solution 4:

A more robust adaptation of Aparna's answer, you can use the $document service which acts as a wrapper for the browser's 'window.document' object. So instead of accessing 'document' variable globally you can access the '$document' object as a dependency. This helps to make your code more testable.

eg:

app.controller('exampleCtrl', function($scope, $document) {
  $scope.deleteArticle = function(id) {
    var articleRow = angular.element($document[0].querySelector('div[data-articleid="'+id+'"]'));
    articleRow.remove();
  };
});

Post a Comment for "Remove HTML Element On Click In Angular Js"