title: AngularJS - Using local variables inside directive
body: <p>I'm having trouble understanding how directives js scope works. I mean it looks like local variables declared in the main directive function are shared among all instances of the directive. Eg.</p>
  
  <pre><code>// HTML
  &lt;ul&gt;
      &lt;li my-dir="1"&gt;&lt;/li&gt;
      &lt;li my-dir="2"&gt;&lt;/li&gt;
      &lt;li my-dir="3"&gt;&lt;/li&gt;
  &lt;/ul&gt;
  
  //JS
  .directive('myDir', function($timeout) {
      var data, _el;
      function init(){
          _el.text(data);
      }
      function link(scope, el, attrs) {
          _el = el;
          data = attrs.myDir;
          $timeout(init,500);
      }
      return {
          restrict: 'A',
          link: link
      };
  });
  </code></pre>
  
  <p>In the above example I'll get only the last element populated with the last value because <code>_el</code> will each time be assigned a new element. Here you have a plnkr of the above:
  <a href="http://plnkr.co/edit/NXV6w4MZbROhnZ524wvx?p=preview" rel="noreferrer">http://plnkr.co/edit/NXV6w4MZbROhnZ524wvx?p=preview</a></p>
  
  <p>What should I do instead?</p>