Sarath S Nair Sarath S Nair - 7 months ago 113
Javascript Question

Remove element on click - using AngularJS Directive

I want to create an angular directive which is used to remove the element from DOM when user clicks on it. I saw answers from here and tried with both methods given in the answers but not able to replicate the same. This is my code

Index.html

<!DOCTYPE html>
<html lang="en" ng-app="myApp">

<head>
<title>abc</title>
<meta charset="UTF-8">
<script src="angular.min.js"></script>
<script src="script.js"></script>
</head>

<body>
<p remove-me>Remove This Element</p>
</body>

</html>


script.js

var app = angular.module('myApp', []);
app.directive("removeMe", function($rootScope) {
return {
link:function(scope,element,attrs)
{
element.bind("click",function() {
element.remove();
});
}
}
});


I am getting the below error on page loading

Console-Error

angular.min.js:117 Error: [$injector:unpr] http://errors.angularjs.org/1.5.5/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20removeMeDirective
at Error (native)
at file:///C:/Users/SARATH%20S%20NAIR/Desktop/abcd/angular.min.js:6:412
at file:///C:/Users/SARATH%20S%20NAIR/Desktop/abcd/angular.min.js:43:84
at Object.d [as get] (file:///C:/Users/SARATH%20S%20NAIR/Desktop/abcd/angular.min.js:40:344)
at file:///C:/Users/SARATH%20S%20NAIR/Desktop/abcd/angular.min.js:43:146
at d (file:///C:/Users/SARATH%20S%20NAIR/Desktop/abcd/angular.min.js:40:344)
at e (file:///C:/Users/SARATH%20S%20NAIR/Desktop/abcd/angular.min.js:41:78)
at Object.invoke (file:///C:/Users/SARATH%20S%20NAIR/Desktop/abcd/angular.min.js:41:163)
at file:///C:/Users/SARATH%20S%20NAIR/Desktop/abcd/angular.min.js:52:329
at q (file:///C:/Users/SARATH%20S%20NAIR/Desktop/abcd/angular.min.js:7:355)

Answer

You can't inject $scope like you are trying to do. This is not a service you can inject in directive. Correct code:

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