JSFiddle - React, Tailwind, and code Playground

by jtassin

HTML

<div ng-app="myApp">
<form novalidate focus-first>
<div>
  <input focusable ng-model="f1" name="f1" type="text" required />
</div>
<input focusable ng-model="f2" name="f2" type="text" required />
<input type="submit" />
</form>
</div>

JavaScript

const app = angular.module('myApp', []);

app.directive('focusable', () => ({
  restrict: 'A', 
  require: '?ngModel',
  link: function(scope, element, attrs, ngModel) {
    ngModel.$$boundElement = element;
  }
}));

app.directive('focusFirst', () => ({
	restrict: 'A',
  link: (scope, element, attrs) => {
    element.on('submit', (event) => {
      event.preventDefault();
      const formCtrl = angular.element(event.target).controller("form");
      const errorKeys = Object.keys(formCtrl.$error);
      if (errorKeys.length > 0) {      
        errorKeys.forEach((errorKey) => {
          // Pretty ugly, it needs to be improved
          const boundElement = formCtrl.$error[errorKeys[0]][0].$$boundElement[0];
          if (boundElement) {
            boundElement.focus();
            // boundElement.scrollIntoView(); // Drive Fiddle crazy
          }
        });
      } else {
        alert('OK !!!');
      }      
    })
  }
}));