NgFocus does not work in AngularJS

Below is a code snippet in which I need to focus the input field based on the value of the checkbox. If I check the box, it should focus on the second element, which somehow does not work. Let me know what I'm doing wrong here with Angular.

Note. I have already tested some examples using directives, but I want to know what I do not see 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

+4
source share
2 answers

ng-focus is used for

Specify custom behavior in the focus event

do not set focus.

angular -docs

,

+5

ngFocus , . ngFocus , .

var, . :

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

html, :

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

plunkr

Alex Emberex.com .

+5

Source: https://habr.com/ru/post/1625326/


All Articles