0

I have a text-box to show a input field on click and hide it on blur. The problem is when the input is shown, it is not auto-focused. The blur only works if you click the text-box, then click the input. But when you click the text-box once and go somewhere else, you can still see the input. Is it possible to auto-focus the input field on click? or maybe there is a better way to do this?

<div data-ng-init="editMode = false">
    <p data-ng-show="!editMode" data-ng-click="editMode = true">{{color}}</p>
    <span data-ng-show="editMode">
       <input data-ng-blur="editMode = false" data-ng-model="color">
    </span>
  </div>

Thanks in advance for your help!

3 Answers3

0

You can apply "autofocus" for the input.

<div data-ng-init="editMode = false; color='Green'">
<p data-ng-show="!editMode" data-ng-click="editMode = true">{{color}}</p>
<span data-ng-show="editMode">
   <input data-ng-blur="editMode = false" data-ng-model="color" autofocus>
</span>

NNguyen
  • 216
  • 2
  • 7
0

reference: Input autofocus attribute

angular.module('ng').directive('autoFocus', function($timeout) {
    return {
        link: function ( scope, element, attrs ) {
            scope.$watch( attrs.autoFocus, function ( val ) {
                if ( angular.isDefined( val ) && val ) {
                    $timeout( function () { element[0].focus(); } );
                }
            }, true);

            element.bind('blur', function () {
                if ( angular.isDefined( attrs.autoFocusLost ) ) {
                    scope.$apply( attrs.autoFocusLost );

                }
            });
        }
    };
});
cccross
  • 76
  • 7
-2

I would suggest maybe making some light use of jquery. Call a function from ng-click, which executes jquery to do an auto-focus, like so:

$("#textInputId").focus();
Jack Zach Tibbles
  • 800
  • 1
  • 11
  • 27