2

I don't want to write complicated directive just to focus something. If the approach would be using the pure js it is acceptable. My question is how to catch the ng-show of angular.

<a ng-click="showInput=true">show</a>
<input type="text" ng-show="showInput" />

the above code show the input, how to focus it upon it appearance?

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
user3398172
  • 811
  • 1
  • 8
  • 13
  • not sure if it's necessary for your project, but keep in mind you cannot programmatically trigger `focus` into elements on iOS devices (it has to be done via a click/tap), however you can traverse the elements once the first focus is set http://stackoverflow.com/questions/18728166/programatically-focus-on-next-input-field-in-mobile-safari – haxxxton Apr 01 '14 at 04:20

2 Answers2

5

You can add this directive:

app.directive('showFocus', function($timeout) {
  return function(scope, element, attrs) {
    scope.$watch(attrs.showFocus, 
      function (newValue) { 
        $timeout(function() {
            newValue && element.focus();
        });
      },true);
  };    
});

and use it like this:

<input type="text" ng-show="showInput" show-focus="showInput">
ezsi
  • 302
  • 3
  • 4
-2

You can try using a simple directive like this one:

app.directive('FocusOnVisibility', function () {
    return function (scope, element, attrs) {
        //Watch the showInput model
        scope.$watch('showInput', function () {
            //If the model changes to true, focus on the element
            if (scope.showInput === true) {
                //Assumes that the element has the focus method
                //If not, then you can have your own logic to focus here
                element.focus();
            }
        });
    };
});

You can then use this directive in your tag as:

<input type="text" ng-show="showInput" focus-on-visibility>
callmekatootie
  • 10,989
  • 15
  • 69
  • 104