How to Catch Directive Deletion
The AngularJs framework of javascript is a trendy and very useful thing. If you an AngularJs developer, you probably know about AngularJs Directives.AngularJs directives let us use the code more by "OOP" mode. It's like "Classes".You can create a directive and use a lot of objects with the type of that directive.
As you saw, ngRepeat, ngClick, ngShow, ngHide, etc.. all of this is AngularJs directives.Lets talk a little about ngRepeat directive.
Catching Directive Deletion
ngRepeat is popular directive and is very useful. You can use it wherever you want. You can create a directive and use the object of that directive type with ngRepeat.With that way, you can use a lot of objects.
Lets see an example:
<script>
angular.module('MyModule',[...])
.directive('myDirective',function(){...});
</script>
...
<my-directive ng-repeat="item in items"></my-directive> // if you create a directive with "Restrict: E"
Now let's imagine a moment, that you want to know where the directive has been removed (if you use ngRepeat with them and remove any item from the array). You probably think that why do I need to know when the directive has been removed. Just for example. You have any points in your database and want to draw it on the map. You will read that data from the database, send it to AngularJs and AngularJs must to draw them.
You can create a directive called Marker, and use it on your data.It looks like this:
<script>
angular.module('Map', [...])
.directive('marker', function(){...}) // this directive will draw the markers on the map
</script>
...
<marker ng-repeat="marker in dbMarkers"></marker> // markers on the map
Let's think you want to remove any item(marker). You can remove only its item in the array, and ngRepeat will do it for you. But the marker will not remove from the map, and you will see not be sure. Have you removed the item or not? have you removed the right item? So what to do?
Here is the solution.Every DOM item (directive) has event $destroy.That event runs before your item will remove. So you can use it like this
angular.module('MyModule')
.drective('marker', function(){
return {
...
link: function(scope,el,...){
el.bind('$destroy',function(){
// do whatever you want
// for example marker.setMap(null) to remove the marker from the map.
})
}
}
})