Angular: Empty Fiddle
http://angularjs.org/
HTML
<script type="text/ng-template" id="tpl.html">
<div>Hai</div>
</script>
<div ng-controller="OuterController">
<test-directive tpl="tpl.html" ctrl="TestDirectiveController" third-party-content="{{thirdPartyContent}}"></test-directive>
<button ng-click="closePopup()">Close that popup</button>
</div>
JavaScript
var app = angular.module('app', []);
app.controller('OuterController', function ($scope, TestDirectiveService) {
$scope.thirdPartyContent = '<h1>Hola!</h1>';
$scope.closePopup = function () {
var openPopups = TestDirectiveService.getAllPopups();
angular.forEach(openPopups, function (scope) {
scope.$emit('$destroy', {});
});
};
});
app.service('TestDirectiveService', function () {
var activePopups = [];
this.registerPopup = function (scope) {
activePopups.push(scope);
};
this.deregisterPopup = function (scope) {
var index = activePopups.indexOf(scope);
if (index !== -1) {
activePopups.splice(index, 1);
}
};
this.getAllPopups = function () {
return activePopups;
};
});
app.controller('TestDirectiveController', function ($scope, $element, $attrs, TestDirectiveService) {
var ctrl = this;
ctrl.init = function () {
ctrl.switchInnerContent($attrs.thirdPartyContent);
TestDirectiveService.registerPopup($scope);
};
ctrl.switchInnerContent = function (content) {
$element[0].innerHTML = content;
};
// Exposed fn to be called from $scope if need be.
$scope.exposedFn = ctrl.switchInnerContent;
$scope.$on('$destroy', function (e, data) {
e.stopPropagation();
$element.html('');
TestDirectiveService.deregisterPopup($scope);
});
});
app.directive('testDirective', function ($controller) {
return {
restrict: 'E',
scope: true,
replace: true,
templateUrl: function (tEl, tAttrs) {
return tAttrs.tpl;
},
controller: function ($scope, $element, $attrs) {
return $controller($attrs.ctrl, {
$scope: $scope,
$element: $element,
$attrs: $attrs
});
},
link: function (scope, el, attrs, controller) {
controller.init();
}
}
});