title: AngularJS compiled code staying "in the back"
body: <p>I've noticed what seems to be a bug for me, but is probably more me misusing the <code>$compile</code> service in AngularJS : I have a directive called "dynamic" that compiles angularjs code and shows it into a div. The code that I compile in that case contains <code>ng-controllers</code> and those controllers are listening on events. The problem is that apparently controllers aren't "dead" after being replaced, because controllers that should be vanished still react to events (like <code>$routeChangeSuccess</code> or any other event).
  Here is a working <a href="http://plnkr.co/edit/YIMGKtLkHGvrOudrCPn7?p=preview" rel="nofollow">plunkr</a> that shows the problem.
  Let's see an example code of my problem :</p>
  
  <p><strong>The directive I'm using</strong> : </p>
  
  <pre><code>app.directive('dynamic', function ($compile) {
      return {
          restrict: 'A',
          replace: true,
          link: function (scope, element, attrs) {
              scope.$watch(attrs.dynamic, function(html) {
                  element.html(html);
                  $compile(element.contents())(scope);
              });
          }
      };
  });
  </code></pre>
  
  <p><strong>The main controller, followed by the controllers that I include:</strong></p>
  
  <pre><code>app.controller('TestCtrl', function($scope) {
    $scope.dynamicContent = "Default content";
  
    $scope.firstButton = function() {
      $scope.dynamicContent = "&lt;div ng-controller='FirstCtrl'&gt;The div from first button&lt;/div&gt;";
    }
  
    $scope.secondButton = function() {
      $scope.dynamicContent = "&lt;div ng-controller='SecondCtrl'&gt;The div from second button&lt;/div&gt;";
    }
  
    $scope.checkButton = function() {
      $scope.$broadcast('checkEvent');
    }
  });
  
  app.controller('FirstCtrl', function($scope) {
    $scope.$on('checkEvent', function() {
      alert(1);
    });
  
  });
  app.controller('SecondCtrl', function($scope) {
    $scope.$on('checkEvent', function() {
      alert(2);
    });
  });
  </code></pre>
  
  <p>Now if I call <code>firstButton()</code> then <code>secondButton()</code> then <code>checkButton()</code>, instead of receiving only the <code>alert(2)</code>, I receive two alerts. If I hit buttons 1/2/1/2/1/2/1/2 it's going to show me as many alerts as buttons I've clicked.</p>
  
  <p>What am I doing wrong here ?</p>
  
  <p>Thanks, hilnius </p>