title: In AngularJS, how do I track a watcher to a view and delete them automatcally as the view is removed or replaced?
body: <p><b>I’m new to AngularJS (a few days) so I’m having a bit of trouble with it.</b><br>
  <br>
  I’m trying to create an equivalent to <code>ng-bind-html</code>, but more permissive.<br>
  I’ve searched all over and managed to get it to accomplish mostly everything I need.<br>
  In short I want to do this<br>
  <code>&lt;div template-compile-unsafe="code"&gt;&lt;/div&gt;</code><br>
  Where <code>code</code> is <code>$scope.code</code>.  As the value of <code>$scope.code</code> is modified it is recompiled into HTML and inserted into the DIV tag.  I’ve even managed to get it to evaluate Angular expressions and create code that even has binding.<br>
  For example set <code>$scope.code</code> this String<br>
  <code>"&lt;input type='text' ng-model='txtInput'&gt;&lt;br&gt;{{txtInput}}"</code><br>
  and you get what is expected.<br>
  But the problem is that when I change the code and it recompiles, it doesn’t delete the old watchers, but keeps adding more.  Examine <code>$scope.$$watchers</code> to see that.<br>
  <br>
  <b>To solve this I’ve tried the following:</b><br>
  - Storing the return function for <code>$scope.$watch(…)</code>, but it doesn’t seem to work when I accumulate more functions.<br>
  <br>
  - I’ve tried adding identifying variables in <code>$scope.$$watchers[n]</code> object to keep track of the particular watcher, but they’re quickly purged every time a new watcher is added to this array.<br>
  <br>
  - So far I haven’t seen anyway way to automatically unbind a watcher if the view is removed or replaced.  I’ve looked into <code>$destroy</code> I can’t seem to make that work unless I destroy the <code>$scope</code>, but that doesn’t help because I only need particular watchers removed.<br>
  <br>
  - I’ve tried <code>element.on(“$destroy”, …)</code><br>
  <br>
  - I can’t use <code>$routeProvider</code> because I need to change only specific areas in the DOM often independent of each other.  That and I can’t have the URL suddenly keep changing if the user is presses a key when typing.<br>
  <br>
  - And I’ve even tried ignoring the problem, but as watchers accumulate the <code>$scope.$watch(…)</code> calls progressively increase to accomplish the same model-view updating.  When I use this in larger and more complex applications or start nesting <code>&lt;div template-compile-unsafe="code"&gt;&lt;/div&gt;</code> the web app becomes noticeably slower in a very short period of time.<br>
  <br>
  The whole point of this is to dynamically load robust templates with Angular expressions and directives to easily swap out tiny to large portions of a site.<br>
  <br>
  <b>See what I have so far <a href="http://jsfiddle.net/bennyhoward/tvnzt2aL" rel="nofollow">here</a> please feel free to edit.  In fact I encourage it.</b></p>