Angular Directive Destroy
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<div ng-controller="ctrl">
<ol>
<li>Press the 'Remove directive good' and then press alert.</li>
<li>Press the 'Remove directive bad' and then press alert. You can see it destroyed the controller's scope</li>
</ol>
<input type="text" ng-model="name"/>
<button ng-click="alertName()">alert</button>
<div remove-directive-good></div>
<div remove-directive-bad></div>
</div>
JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('ctrl', function($scope) {
$scope.name = "Matt";
$scope.alertName = function() {
alert($scope.name);
};
});
myApp.directive('removeDirectiveGood', function() {
return {
scope: true,
template: "<button ng-click='removeDirective()'>Remove directive good</button>",
link: function(scope, element, attrs) {
scope.removeDirective = function() {
/* This is destroying the scope of just the directive */
scope.$destroy();
element.remove();
};
}
};
});
myApp.directive('removeDirectiveBad', function() {
return {
template: "<button ng-click='removeDirective()'>Remove directive bad</button>",
link: function(scope, element, attrs) {
scope.removeDirective = function() {
/* This is destroying the controller's scope
because I didn't define a scope. */
scope.$destroy();
element.remove();
};
}
};
});