For this you can use the directive with event handling.
Updated Fiddle
Key changes are as follows:
1) Download jQuery into your script before angular so that you can access jQuery selectors inside angular functions.
2) Wrap your entries in the container with the appropriate directive (Note: this can also be done with a single element with restrict: "E" instead of restrict: "A" and use the template property to define the child HTML)
3) Handle the input event on the inputs, and if the length exceeds the value in the maxlength property, focus the next input. It is really simple with jQuery, but can be done unnecessarily if you really want to.
4) There are a million ways to test inputs, but I have included a simple method.
HTML
<div phone-input> <input type="text" value="" maxlength="3" class="area-code input-mini aid-primary-phone1-lbl" aria-label="Primary contact number" pattern="^[0-9]{3}$"> <input type="text" value="" maxlength="3" class="area-code input-mini aid-primary-phone2-lbl" aria-label="Primary contact number" pattern="^[0-9]{3}$"> <input type="text" value="" maxlength="4" class="area-code input-mini aid-primary-phone3-lbl" aria-label="Primary contact number" pattern="^[0-9]{4}$"> </div>
Angular Directive
.directive("phoneInput", function () { return { restrict: "A", link: function (scope, element, attrs) { function checkForErrors(input) { var errors = ""; if (!new RegExp(input.attr("pattern")).test(input.val())) { errors += `Field must contain ${input.attr("maxlength")} numbers!\n`; } return errors; } element.on("input", "input", function () { var trigger = $(this); if (trigger.val().length >= trigger.attr("maxlength")) { trigger.blur().next().focus(); } }); element.on("blur", "input", function () { var trigger = $(this); var errors = checkForErrors(trigger); trigger.attr("title", errors); if (trigger.val().trim() === "") { trigger.addClass("invalid-field"); trigger.attr("title", "Field cannot be empty!"); } else if (errors === "") { trigger.removeClass("invalid-field"); } else { trigger.addClass("invalid-field"); trigger.focus(); } }); } } })
mhodges
source share