2

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";
   };
};
Bobby King
  • 791
  • 2
  • 7
  • 7
  • See CodePen version: http://codepen.io/angeltapes/pen/KwZVaZ – Bobby King Feb 10 '15 at 10:27
  • Is the 'focus' attribute on the input element a directive? – Viktor Feb 10 '15 at 10:31
  • There is no focus attribute in html, so as long as there is no JS is actually calling `.focus()` on the element nothing will happen. You could use `$element.find()` to get the input and then call `.focus()` on it yourself. – Dehalion Feb 10 '15 at 10:32

3 Answers3

5

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

icl7126
  • 5,740
  • 4
  • 53
  • 51
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.

Community
  • 1
  • 1
Viktor
  • 257
  • 1
  • 5
-3

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"));
   }
});
gari
  • 95
  • 7
  • 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. – Banjocat Feb 28 '16 at 19:33