Bobby King
Bobby King

Reputation: 801

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

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";
   };
};

Upvotes: 2

Views: 43309

Answers (3)

Juraj
Juraj

Reputation: 6638

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);

Upvotes: 5

gari
gari

Reputation: 95

I have modified your code, check it.

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


var app = angular.module('TestApp', []);

app.controller('personController', function ($scope, $http, $log) {

   $scope.focus = function () {
     $("#question1").focus();
    console.log($("#question1"));
   }
});

Upvotes: -3

Viktor
Viktor

Reputation: 257

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.

Upvotes: 2

Related Questions