ngFocus not working in AngularJS

亡梦爱人 提交于 2020-01-02 05:27:07

问题


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


回答1:


ng-focus is used to

Specify custom behavior on focus event

not to set focus.

check angular-docs

To meet your case refer here




回答2:


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.



来源:https://stackoverflow.com/questions/34924156/ngfocus-not-working-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!