I implemented a modal window triggered by fancybox in my project. Once the modal is displayed, fancybox triggers a "modalShown" event that is listened for by AppController. In this listener, $compile is called on the modal content to create the ModalController, interpolate, and bind events on the view.
However, I'm facing an issue where even after closing the modal, the modal element is removed from the DOM but its bound ModalController instance remains somewhere in the app. Consequently, every time a new modal is opened, a new controller is created, leading to multiple orphaned controllers responding to events within the modal window.
My main concern is regarding cleaning up these unused controllers scattered throughout my application, as $compile doesn't provide a reference to the newly created controller.
Snippet of relevant code (written in CoffeeScript)...
Fancybox Directive
# Setting up fancybox on elements triggering the modal...
# <a href="#" fancybox="templateToLoad.html">Trigger Modal</a>
@app.directive 'fancybox', ["$templateCache", "$compile", ($templateCache, $compile) ->
(scope, element, attrs) ->
options =
afterShow : ->
scope.$root.$broadcast 'modalShown', scope
element.fancybox options
modal.html
<div class="fancybox-skin">
<div class="fancybox-outer">
<div class="fancybox-inner ng-scope">
<div ng-controller="ModalController" style="..." class="ng-scope">
<a href="#" ng-click="someAction()">Some Action in ModalController</a>
</div>
</div>
</div>
</div>
ModalController
app.controller 'ModalController', [
'$scope', '$rootScope',($scope, $rootScope) ->
# Tracking controllers for debugging
window.globalCounter ||= 0
$scope.localCounter = window.globalCounter++
someAction = () ->
console.log 'action'
AppController
@app.controller "AppController", [
"$scope", "$rootScope", "$compile", ($scope, $rootScope, $compile) ->
$scope.$on 'modalShown', (e, localScope) ->
console.log('compiling modal contents')
$compile($('.fancybox-inner'))(localScope)
$rootScope.$apply()