0
votes

I'm trying to create a directive that would "control" two input boxes (there will be several of these directives on a page created with ng-repeat). The functionality that I can't find a solution for is focus.

Input boxes need to switch focus between them in each directive (ie. once I select one input box and press enter, focus needs to go to it's "sibling" input, press enter there and focus goes back to first input etc.). Focus never leaves a directive (ie. one of the two input boxes) unless I select another input in another directive.

Is there any elegant AngularJS solution for this behavior? Or, if not, is there any solution not involving jQuery?

2

2 Answers

0
votes

One way you could do it is by binding a listener on keypress, which will $broadcast the event. The same directive can listen for that event, matching to make sure it's not the same element who broadcasted the event before focusing itself.

.directive('myDirective', function(){
  return {
    scope: true, // necessary for use with ng-repeat
    link: function(scope, elem, attrs) {
      scope.$on('enter', function($event, argElem){
        if (elem !== argElem) elem[0].focus();
      });
      elem.on('keypress', function($event){
        if ($event.keyCode === 13) {
          scope.$parent.$broadcast('enter', elem);
        }
      });
    }
  }
})

Note: Updated from original response to allow for use with ng-repeat

Demo

0
votes

ASSOCIATED SAMPLE with ng-repeat usage

You can create a directive that will accept the id of the element that you can focus when you press enter. Simply use the document.getElementBy or $document[0].getElementById(for testing purposes) to get the element to be focused. Bind an event keypress to the current element context of your directive and trigger an element focus when you press enter.

e.g.

JAVSCRIPT

.directive('simpleNextFocus', function(/*$document*/) {
  return function(scope, elem, attr) {
    if(attr.simpleNextFocus) {
      elem.on('keydown', function(e) {
          if(e.keyCode == 13) {
            // $document[0].getElementById(attr.simpleNextFocus).focus();
            document.getElementById(attr.simpleNextFocus).focus();
          }
        });
    }
  };
})

HTML

<input type="text" id="input-1" simple-next-focus="input-2">
<input type="text" id="input-2" simple-next-focus="input-1">