<!DOCTYPE html>
<html>
<head>
<script data-require="angularjs@1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="scopeDestroyTest">
<h1>Hello Plunker! {{includedTemplate}}</h1>
<div class="info"
ng-init="testResult={}">
Enter 1 or 2 here to include one of the templates.
Template 1 registers the scope destroy listener
and switching to template 2 just causes this scope
to be destroyed
</div>
<label>Template no (1/2):</label>
<input type='text' ng-model='includedTemplate'/>
<div class="info important" ng-if="testResult.message1">
<div>{{testResult.message1}}</div>
<div>{{testResult.message2}}</div>
</div>
<ng-include src='"include1.html"' ng-if="includedTemplate==1"></ng-include>
<ng-include src='"include2.html"' ng-if="includedTemplate==2"></ng-include>
</body>
</html>
(function(angular){
angular.module('scopeDestroyTest',[])
.directive('tapDestroy',function(){
return{
restrict:'E',
scope:true,
link:function($scope){
console.log('Tapping destroy for ',$scope.$id);
$scope.testResult={
message1 : "Tapped destroy for scopeId: "+$scope.$id,
message2: null
};
$scope.$on('$destroy',function($event){
$scope.testResult.message2 = "Destroy event caught for scopeId: "+$event.targetScope.$id;
console.log('Scope destroyed',$event);
})
}
}
})
}(angular));
.info{
border: 1px solid gainsboro;
box-shadow:3px 3px 10px #D7D9DB;
margin:20px 0px;
padding:10px;
color:gray;
}
.info.important{
border-color:red;
}
<tap-destroy>
<div class=info>Included 1. Tapped destroy for scopeId = {{this.$id}}. </div>
<div>And this scope contains property with value, {{value}}.</div>
<input type='text' ng-model="value" />
</tap-destroy>
<div class="info">
Include 2.
Does absolutely nothing, but does ensure that any previous ng-include, ng-if scopes get destroyed.
Check console for information on the scope that got destroyed.
</div>