Sarath S Nair Sarath S Nair - 2 years ago 271
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


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

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

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



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

I am getting the below error on page loading


angular.min.js:117 Error: [$injector:unpr]$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 Source

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() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download