Set conditional focus on some field in the corner

Hello to all fellow engineers, I have seen so many questions and offer answers to questions regarding setting focus to some input field, but I did not find anything that would meet my requirements, now my question is that we have several input fields and we don't know where to set focus, and on some specific condition I want to set focus on some field back from the controller, is there something like "document.getElementbyId (" "). focus" like in javascript with "ng-model" or something, any help would be appreciated thanks

+3


source to share


1 answer


This directive will cause the element to receive focus when passed in expression is true.

Live Demo

Using:



<!-- set `$scope.foo` to a truthy value when this input should be focused -->
<input type="text" focus-when="foo">
<button ng-click="foo = true">Focus input.</button>

      

Directive:

.directive('focusWhen', function() {
  return {
    scope: {
      focusWhen: '='
    },
    link: function($scope, $element) {

      $scope.$watch('focusWhen', function(shouldFocus) {
        if (shouldFocus) {
          $element[0].focus();
        }
      });

    }
  };
})

      

+4


source







All Articles