title: AngularJS ngShow and focus
body: <p>Attempting to show a <code>textarea</code> in Angular based on whether or not a <code>preview</code> variable is true. After <code>preview</code> is set to true I'd like to set focus to the <code>textarea</code> as well. </p>
  
  <p><strong>Controller Logic</strong></p>
  
  <pre><code>.controller('MyCtrl', ['$scope', function ($scope) {
      $scope.preview = false;
      $scope.showPreview = function() {
          $scope.preview = true;
      }
  }])
  </code></pre>
  
  <p><strong>Directive Logic</strong></p>
  
  <pre><code>.directive('previewFocus', function() {
      return function(scope, element, attrs) {
         scope.$watch('preview', 
           function (newValue) { 
              newValue &amp;&amp; element[0].focus();
           },true);
        };    
  });
  </code></pre>
  
  <p>Then I have a <code>div</code> that when clicked, it will fire off the <code>showPreview()</code> method:</p>
  
  <pre><code>&lt;div ng-click="showPreview()"&gt;Add Post&lt;/div&gt;
  </code></pre>
  
  <p>And a <code>textarea</code> with the <code>preview-focus</code> directive:</p>
  
  <pre><code>&lt;textarea class="previewInput" preview-focus&gt;&lt;/textarea&gt;
  </code></pre>
  
  <p>I've debugged the code and everything executes as expected, including the callback on the <code>scope.$watch</code> function. However, the <code>textarea</code> does not take focus. If I don't use the <code>ngShow</code> directive, the focus works fine. Below are two JSFiddle examples to show both cases.</p>
  
  <p><strong>Focus does not work</strong>: <a href="http://jsfiddle.net/Dm5LG/1/" rel="nofollow">JSFiddle with ngShow</a></p>
  
  <p><strong>Focus works fine</strong>: <a href="http://jsfiddle.net/FF9wC/1/" rel="nofollow">JSFiddle without ngShow</a></p>
  
  <p>Does anyone know of a good way to use <code>ngShow</code> and focus the element being showed at the same time? </p>