title: Set focus to first invalid form element in AngularJS
body: <p>Basically, what I'm trying to accomplish, is to set focus to the first invalid element after a form submit has been attempted. At this point, I have the element being flagged as invalid, and I can get the <code>$name</code> of the element so I know which one it is.</p>
  
  <p>It's "working" but a "$apply already in progress" error is being thrown... 
  <br>So I must be doing something wrong here :)</p>
  
  <p>Here's my code so far:</p>
  
  <pre><code>$scope.submit = function () {
  
      if ($scope.formName.$valid) {
          // Good job.
      }
      else 
      {
          var field = null,
              firstError = null;
          for (field in $scope.formName) {
              if (field[0] != '$')
              {
                  if (firstError === null &amp;&amp; !$scope.formName[field].$valid) {
                      firstError = $scope.formName[field].$name;
                  }
  
                  if ($scope.formName[field].$pristine) {
                      $scope.formName[field].$dirty = true;
                  }
              }
          }
  
          formName[firstError].focus();
      }
  }
  </code></pre>
  
  <p>My field looping is based on <a href="https://stackoverflow.com/questions/18324773/force-ng-dirty-in-angularjs-form-validation">this solution</a>, and I've read over <a href="https://stackoverflow.com/questions/14833326/how-to-set-focus-in-angularjs">this question</a> a few times. It <em>seems</em> like the preferred solution is to create a directive, but adding a directive to every single form element just seems like overkill.</p>
  
  <p>Is there a better way to approach this with a directive?</p>