4

Following is my code snippet in which I need to focus an input field on the basis of checkbox value, If I check the checkbox it should focus the second element which somehow not working. Let me know what i am doing wrong here with Angular.

Note - I already checked few examples using directives, but I want to know what I am missing here concept/code etc

<input type="checkbox" ng-model="vm.check" />
<br>
<input type="text" ng-model="vm.input1" />
<input type="text" ng-model="vm.input2" ng-focus="vm.check" />
<input type="text" ng-model="vm.input3" />

Plnkr Code - http://plnkr.co/edit/q15Jht9AsVj60xrutVfm?p=preview

Nesh
  • 2,389
  • 7
  • 33
  • 54
  • 1
    normally the expression of `ng-focus` is a event handler which will handle whatever you want to do on focusing the element, is that what you want to do? you may find more from the [documentation](https://docs.angularjs.org/api/ng/directive/ngFocus). – Roy Ling Jan 21 '16 at 13:39

2 Answers2

8

ngFocus doesn't work the way you think. The expression under ngFocus is triggered on input focus, that's all.

If you want to focus it depending on the state of a var, you should use a directive. Example :

myApp.directive('syncFocusWith', function($timeout, $rootScope) {
  return {
    restrict: 'A',
    scope: {
      focusValue: "=syncFocusWith"
    },
    link: function($scope, $element, attrs) {
      $scope.$watch("focusValue", function(currentValue, previousValue) {
        if (currentValue === true && !previousValue) {
          $element[0].focus();
        } else if (currentValue === false && previousValue) {
          $element[0].blur();
        }
      })
    }
  }
});

And update your html to use this directive :

<input type="text" ng-model="vm.input2" sync-focus-with="vm.check"/>

Updated plunkr

Credits to Alex from Emberex.com for sharing this snippet.

Maen
  • 10,603
  • 3
  • 45
  • 71
6

ng-focus is used to

Specify custom behavior on focus event

not to set focus.

check angular-docs

To meet your case refer here

Community
  • 1
  • 1
lintu
  • 1,092
  • 11
  • 24