Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngFocus not working in AngularJS

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

like image 975
Nesh Avatar asked Dec 09 '22 00:12

Nesh


1 Answers

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.

like image 166
Bigood Avatar answered Dec 29 '22 15:12

Bigood