Reputation: 613
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)
Upvotes: 1
Views: 3424
Reputation: 193301
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();
});
}
}
});
Upvotes: 3
Reputation: 48
Check this answer here https://stackoverflow.com/a/21595931/2700949 It seemes you should use $rootScope and not $scope.
var app = angular.module('myApp', []);
app.directive("removeMe", function() {
return {
link:function(scope,element,attrs)
{
element.bind("click",function() {
element.remove();
});
}
}
});
<div class="showw" ng-app="myApp">
<div id="hideDivOnClick" src="ddd.png" remove-me>Click me</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Upvotes: 1
Reputation: 361
Try to use this sample. In my case it's worked.
in HTML
<button permission-code="'12012'" type="button">Email</button>
in Script.js
angular.module("myApp").directive("permissionCode", function () {
return {
restrict: 'A',
scope: {
permissionCode: "="
},
controller: ["$scope", "$element", function ($scope, $element) {
if ($scope.permissionCode == '12012') {
angular.element($element).remove();
}
}]
};
});
Upvotes: 0