angular js - using ng-click to focus on a text box

43,037

Solution 1

How about some general solution ($ is jQuery):

mod.directive('nsFocusId', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs, ctrl) {
      element.click(function() {
        $timeout(function () { $('#' + attrs.nsFocusId).focus(); }, 0);
      });
    }
  };
}]);

Usage:

<label data-ns-focus-id="id-of-target-element">a</label>

This directive could be used on any element and it will focus element by id that you provide.
I've used $timeout just to make it more flexible for future upgrades (but feel free to wrap it with just scope.$apply function);

Solution 2

https://docs.angularjs.org/api/ng/directive/ngFocus

ng-focus executes an expression when the element is focused, so it doesn't actually set the element as focused but rather respond to it being focused.

How to set focus on input field?

Check this resource or google up 'how to set an element focused' and it should direct you in the right way.

Share:
43,037
Bobby King
Author by

Bobby King

Updated on October 22, 2020

Comments

  • Bobby King
    Bobby King over 3 years

    I'm trying to build an Angular JS form. I'd like user to be able to set the focus on a text field when they click a button. Not sure why this doesn't work? Thanks

    html:

    <div ng-app="" ng-controller="personController">
      <p>Name: <input type="text" ng-model="name" id="question1" focus="{{focusThis}}"></p>
      <p ng-bind="name"></p>
      <input type="button" value="focus" ng-click="focus()">
    </div>
    

    Angular JS function:

    function personController($scope)
       {$scope.focus=function(){
        $scope.focusThis="true";
       };
    };
    
  • Banjocat
    Banjocat about 8 years
    The problem with this is you are tying your angular code to your HTML. Which is what you want to avoid. You want your angular code to work even without an HTML attached to it. This allows for easier testing. I am not the downvoter.. since I can't do that.
  • AlxVallejo
    AlxVallejo over 7 years
    you seriously just answered the question as 'Google It'. Do you want a medal?