your programing

입력 필드에 초점을 설정하는 방법은 무엇입니까?

lovepro 2020. 9. 29. 08:18
반응형

입력 필드에 초점을 설정하는 방법은 무엇입니까?


AngularJS에서 입력 필드에 초점을 맞추는 '각도 방식'은 무엇입니까?

더 구체적인 요구 사항 :

  1. 모달가 열리고, 미리 정의에 포커스를 설정 <input>이 모달 내부.
  2. <input>표시 될 때 마다 (예 : 버튼 클릭) 포커스를 설정합니다.

나는 첫 번째 요구 사항 달성하기 위해 노력 과를 autofocus, 그러나 이것은 모달 처음 열리고 특정 브라우저 (파이어 폭스에서 작동하지 않는 등) 경우에만 작동합니다.

도움을 주시면 감사하겠습니다.


  1. 모달이 열리면이 모달 내부에 미리 정의 된 <입력>에 포커스를 설정합니다.

지시문을 정의하고 속성 / 트리거를 감시하여 요소에 초점을 맞출시기를 알 수 있도록합니다.

Name: <input type="text" focus-me="shouldBeOpen">

app.directive('focusMe', ['$timeout', '$parse', function ($timeout, $parse) {
    return {
        //scope: true,   // optionally create a child scope
        link: function (scope, element, attrs) {
            var model = $parse(attrs.focusMe);
            scope.$watch(model, function (value) {
                console.log('value=', value);
                if (value === true) {
                    $timeout(function () {
                        element[0].focus();
                    });
                }
            });
            // to address @blesh's comment, set attribute value to 'false'
            // on blur event:
            element.bind('blur', function () {
                console.log('blur');
                scope.$apply(model.assign(scope, false));
            });
        }
    };
}]);

플 런커

$ timeout은 렌더링 할 모달 시간을 제공하는 데 필요한 것 같습니다.

'2.' <입력>이 표시 될 때마다 (예 : 버튼 클릭) 포커스를 설정합니다.

본질적으로 위와 같은 지시문을 작성하십시오. 일부 범위 속성을 확인하고 true가되면 (ng-click 핸들러에서 설정) element[0].focus(). 사용 사례에 따라 $ timeout이 필요할 수도 있고 필요하지 않을 수도 있습니다.

<button class="btn" ng-click="showForm=true; focusInput=true">show form and
 focus input</button>
<div ng-show="showForm">
  <input type="text" ng-model="myInput" focus-me="focusInput"> {{ myInput }}
  <button class="btn" ng-click="showForm=false">hide form</button>
</div>

app.directive('focusMe', function($timeout) {
  return {
    link: function(scope, element, attrs) {
      scope.$watch(attrs.focusMe, function(value) {
        if(value === true) { 
          console.log('value=',value);
          //$timeout(function() {
            element[0].focus();
            scope[attrs.focusMe] = false;
          //});
        }
      });
    }
  };
});

플 런커


2013 년 7 월 업데이트 : 몇 사람이 원래의 격리 범위 지시문을 사용하고 내장 입력 필드 (즉, 모달의 입력 필드)에 문제가있는 것을 보았습니다. 새로운 범위 (또는 새로운 자식 범위)가없는 지시문은 일부 고통을 완화해야합니다. 그래서 위에서 격리 범위를 사용하지 않도록 답변을 업데이트했습니다. 다음은 원래 답변입니다.

1. 격리 범위를 사용하여 원래 답변 :

Name: <input type="text" focus-me="{{shouldBeOpen}}">

app.directive('focusMe', function($timeout) {
  return {
    scope: { trigger: '@focusMe' },
    link: function(scope, element) {
      scope.$watch('trigger', function(value) {
        if(value === "true") { 
          $timeout(function() {
            element[0].focus(); 
          });
        }
      });
    }
  };
});

플 런커 .

2. 격리 범위를 사용하여 원래 답변 :

<button class="btn" ng-click="showForm=true; focusInput=true">show form and
 focus input</button>
<div ng-show="showForm">
  <input type="text" focus-me="focusInput">
  <button class="btn" ng-click="showForm=false">hide form</button>
</div>

app.directive('focusMe', function($timeout) {
  return {
    scope: { trigger: '=focusMe' },
    link: function(scope, element) {
      scope.$watch('trigger', function(value) {
        if(value === true) { 
          //console.log('trigger',value);
          //$timeout(function() {
            element[0].focus();
            scope.trigger = false;
          //});
        }
      });
    }
  };
});

플 런커 .

지시문에서 trigger / focusInput 속성을 재설정해야하므로 양방향 데이터 바인딩에는 '='가 사용됩니다. 첫 번째 지시문에서는 '@'로 충분했습니다. 또한 '@'를 사용할 때 @는 항상 문자열이되므로 트리거 값을 "true"로 비교합니다.


(편집 :이 설명 아래에 업데이트 된 솔루션을 추가했습니다)

마크 Rajcok 그 사람 ... 그리고 그의 대답은 올바른 대답이지만, 결함 (죄송 마크)했다 ...

... 부울을 사용하여 입력에 초점을 맞춘 다음 입력을 흐리게 처리 한 다음 입력에 다시 초점을 맞추기 위해 사용합니다. 부울을 false로 재설정 한 다음 $ digest로 재설정 한 다음 다시 true로 재설정하지 않으면 작동하지 않습니다. 식에서 문자열 비교를 사용하더라도 문자열을 다른 $ digest로 변경 한 다음 다시 변경해야합니다. (이는 blur 이벤트 핸들러로 해결되었습니다.)

그래서 저는이 대체 해결책을 제안합니다.

Angular의 잊혀진 기능인 이벤트를 사용하십시오.

JavaScript는 결국 이벤트를 좋아합니다. 이벤트는 본질적으로 느슨하게 결합되어 있으며 더 좋은 점은 $ digest에 다른 $ watch를 추가하지 않는 것입니다.

app.directive('focusOn', function() {
   return function(scope, elem, attr) {
      scope.$on(attr.focusOn, function(e) {
          elem[0].focus();
      });
   };
});

이제 다음과 같이 사용할 수 있습니다.

<input type="text" focus-on="newItemAdded" />

그리고 앱 어디에서나 ...

$scope.addNewItem = function () {
    /* stuff here to add a new item... */

    $scope.$broadcast('newItemAdded');
};

이런 식으로 모든 종류의 일을 할 수 있기 때문에 이것은 대단합니다. 우선, 이미 존재하는 이벤트에 연결할 수 있습니다. 또 다른 일로, 앱의 다른 부분이 구독 할 수있는 이벤트를 앱의 다른 부분에 게시하도록하여 스마트 한 작업을 시작합니다.

어쨌든, 이런 종류의 것은 나에게 "이벤트 주도"라고 비명을 지른다. Angular 개발자로서 우리는 $ scope 모양의 못을 이벤트 모양 구멍으로 망치려고 정말 열심히 노력한다고 생각합니다.

최상의 솔루션입니까? 몰라요. 그것은이다 솔루션입니다.


업데이트 된 솔루션

아래 @ShimonRachlenko의 의견 이후에이 작업을 수행하는 방법을 약간 변경했습니다. 이제 "뒤에서"이벤트를 처리하는 지시문과 서비스의 조합을 사용합니다.

그 외에는 위에서 설명한 것과 동일한 원칙입니다.

다음은 간단한 데모입니다. Plunk

용법

<input type="text" focus-on="focusMe"/>
app.controller('MyCtrl', function($scope, focus) {
    focus('focusMe');
});

출처

app.directive('focusOn', function() {
   return function(scope, elem, attr) {
      scope.$on('focusOn', function(e, name) {
        if(name === attr.focusOn) {
          elem[0].focus();
        }
      });
   };
});

app.factory('focus', function ($rootScope, $timeout) {
  return function(name) {
    $timeout(function (){
      $rootScope.$broadcast('focusOn', name);
    });
  }
});

나는 당신이 정말로 필요한 모든 것이 이것뿐 일 때 다른 답변 중 일부가 지나치게 복잡하다는 것을 발견했습니다

app.directive('autoFocus', function($timeout) {
    return {
        restrict: 'AC',
        link: function(_scope, _element) {
            $timeout(function(){
                _element[0].focus();
            }, 0);
        }
    };
});

사용법은

<input name="theInput" auto-focus>

우리는 시간 제한을 사용하여 dom의 사물이 렌더링되도록합니다. 비록 그것이 0이더라도 적어도 그것을 기다립니다. 이런 식으로 이것은 모달에서도 작동합니다.


HTML에는 속성이 autofocus있습니다.

<input type="text" name="fname" autofocus>

http://www.w3schools.com/tags/att_input_autofocus.asp


angular에 내장 된 jqlite 기능을 사용할 수도 있습니다.

angular.element('.selector').trigger('focus');


이것은 잘 작동하고 입력 제어에 초점을 맞추는 각도 방식입니다.

angular.element('#elementId').focus()

이것은 작업을 수행하는 순수한 각도 방식은 아니지만 구문은 각도 스타일을 따릅니다. Jquery는 Angular (jQLite => JQuery Light)를 사용하여 간접적이고 직접 DOM에 액세스합니다.

필요한 경우이 코드는 요소에 직접 액세스 할 수있는 간단한 각도 지시문 안에 쉽게 넣을 수 있습니다.


$ timeout이 요소를 창조에 집중하는 좋은 방법이라고 생각하지 않습니다. 다음은 앵귤러 문서의 어두운 깊이에서 파낸 내장 앵귤러 기능을 사용하는 방법입니다. 사전 링크 및 사후 링크 기능에 대해 "링크"속성을 "pre"및 "post"로 분할하는 방법에 유의하십시오.

작업 예 : http://plnkr.co/edit/Fj59GB

// this is the directive you add to any element you want to highlight after creation
Guest.directive('autoFocus', function() {
    return {
        link: {
            pre: function preLink(scope, element, attr) {
                console.debug('prelink called');
                // this fails since the element hasn't rendered
                //element[0].focus();
            },
            post: function postLink(scope, element, attr) {
                console.debug('postlink called');
                // this succeeds since the element has been rendered
                element[0].focus();
            }
        }
    }
});
<input value="hello" />
<!-- this input automatically gets focus on creation -->
<input value="world" auto-focus />

전체 AngularJS 지시문 문서 : https://docs.angularjs.org/api/ng/service/$compile


내 원래 솔루션은 다음과 같습니다.

플 런커

var app = angular.module('plunker', []);
app.directive('autoFocus', function($timeout) {
    return {
        link: function (scope, element, attrs) {
            attrs.$observe("autoFocus", function(newValue){
                if (newValue === "true")
                    $timeout(function(){element[0].focus()});
            });
        }
    };
});

그리고 HTML :

<button ng-click="isVisible = !isVisible">Toggle input</button>
<input ng-show="isVisible" auto-focus="{{ isVisible }}" value="auto-focus on" />

기능 :

ng-show로 표시되는 입력에 초점을 맞 춥니 다. 여기서 $ watch 또는 $ on을 사용하지 않습니다.


최근에 모델과 마찬가지로 양방향 바인딩 포커스 지시문을 작성했습니다.

다음과 같이 focus 지시문을 사용할 수 있습니다.

<input focus="someFocusVariable">

true컨트롤러의 어느 곳에서나 someFocusVariable 범위 변수를 만들면 입력에 초점이 맞춰집니다. 입력을 "흐리게"하려면 someFocusVariable을 false로 설정할 수 있습니다. Mark Rajcok의 첫 번째 답변과 같지만 양방향 바인딩이 있습니다.

다음은 지시문입니다.

function Ctrl($scope) {
  $scope.model = "ahaha"
  $scope.someFocusVariable = true; // If you want to focus initially, set this to true. Else you don't need to define this at all.
}

angular.module('experiement', [])
  .directive('focus', function($timeout, $parse) {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
          scope.$watch(attrs.focus, function(newValue, oldValue) {
              if (newValue) { element[0].focus(); }
          });
          element.bind("blur", function(e) {
              $timeout(function() {
                  scope.$apply(attrs.focus + "=false"); 
              }, 0);
          });
          element.bind("focus", function(e) {
              $timeout(function() {
                  scope.$apply(attrs.focus + "=true");
              }, 0);
          })
      }
    }
  });

용법:

<div ng-app="experiement">
  <div ng-controller="Ctrl">
    An Input: <input ng-model="model" focus="someFocusVariable">
    <hr>
        <div ng-click="someFocusVariable=true">Focus!</div>  
        <pre>someFocusVariable: {{ someFocusVariable }}</pre>
        <pre>content: {{ model }}</pre>
  </div>
</div>

다음은 바이올린입니다.

http://fiddle.jshell.net/ubenzer/9FSL4/8/


Angular를 Bootstrap 플러그인과 함께 사용하는 경우 :

http://angular-ui.github.io/bootstrap/#/modal

opened모달 인스턴스 약속에 연결할 수 있습니다 .

modalInstance.opened.then(function() {
        $timeout(function() {
            angular.element('#title_input').trigger('focus');
        });
    });

modalInstance.result.then(function ( etc...

일반적인 표현을 사용하는 것이 유용하다는 것을 알았습니다. 이렇게하면 입력 텍스트가 유효 할 때 자동으로 초점을 이동하는 등의 작업을 수행 할 수 있습니다.

<button type="button" moo-focus-expression="form.phone.$valid">

또는 사용자가 고정 길이 필드를 완료하면 자동으로 초점을 맞 춥니 다.

<button type="submit" moo-focus-expression="smsconfirm.length == 6">

그리고 물론로드 후 집중

<input type="text" moo-focus-expression="true">

지시문의 코드 :

.directive('mooFocusExpression', function ($timeout) {
    return {
        restrict: 'A',
        link: {
            post: function postLink(scope, element, attrs) {
                scope.$watch(attrs.mooFocusExpression, function (value) {

                    if (attrs.mooFocusExpression) {
                        if (scope.$eval(attrs.mooFocusExpression)) {
                            $timeout(function () {
                                element[0].focus();
                            }, 100); //need some delay to work with ng-disabled
                        }
                    }
                });
            }
        }
    };
});

자신의 지시문을 만드는 대신 자바 스크립트 함수를 사용하여 초점을 맞추는 것이 가능합니다.

여기에 예가 있습니다.

html 파일에서 :

<input type="text" id="myInputId" />

예를 들어 컨트롤러에서 포커스를 활성화하려는 파일 자바 스크립트에서 :

document.getElementById("myInputId").focus();

좀비를 부활 시키거나 내 자신의 지시문을 연결하지 마십시오 (정확히 내가하는 일입니다).

https://github.com/hiebj/ng-focus-if

http://plnkr.co/edit/MJS3zRk079Mu72o5A9l6?p=preview

<input focus-if />

(function() {
    'use strict';
    angular
        .module('focus-if', [])
        .directive('focusIf', focusIf);

    function focusIf($timeout) {
        function link($scope, $element, $attrs) {
            var dom = $element[0];
            if ($attrs.focusIf) {
                $scope.$watch($attrs.focusIf, focus);
            } else {
                focus(true);
            }
            function focus(condition) {
                if (condition) {
                    $timeout(function() {
                        dom.focus();
                    }, $scope.$eval($attrs.focusDelay) || 0);
                }
            }
        }
        return {
            restrict: 'A',
            link: link
        };
    }
})();

첫째, 초점을 맞추는 공식적인 방법 은 1.1로드맵에 있습니다. 한편, 포커스 설정을 구현하는 지시문을 작성할 수 있습니다.

둘째, 항목이 표시된 후에 포커스를 설정하려면 현재 해결 방법이 필요합니다. 요소 focus ()에 대한 호출을 $timeout.

초점, 흐림 및 선택에 대해 동일한 controller-modifies-DOM 문제가 존재하기 때문에 ng-target지시문을 제안 합니다.

<input type="text" x-ng-model="form.color" x-ng-target="form.colorTarget">
<button class="btn" x-ng-click="form.colorTarget.focus()">do focus</button>

Angular 스레드 : http://goo.gl/ipsx4 및 자세한 내용은 여기 블로그 : http://goo.gl/4rdZa

다음 지시문은 속성에 .focus()지정된대로 컨트롤러 내부 함수 를 생성 ng-target합니다. (그것은 생성 .blur()과를 .select()너무.) 데모 : http://jsfiddle.net/bseib/WUcQX/


ng-click으로 제어되는 간단한 포커스를 원하신다면.

HTML :

<input ut-focus="focusTigger">

<button ng-click="focusTrigger=!focusTrigger" ng-init="focusTrigger=false"></button>

지령:

'use strict'

angular.module('focus',['ng'])
.directive('utFocus',function($timeout){
    return {
        link:function(scope,elem,attr){
            var focusTarget = attr['utFocus'];
            scope.$watch(focusTarget,function(value){
                $timeout(function(){
                    elem[0].focus();
                });
            });
        }
    }
});

모달과 잘 작동하는 간단한 것 :

.directive('focusMeNow', ['$timeout', function ($timeout)
{
    return {
        restrict: 'A',

        link: function (scope, element, attrs)
        {


            $timeout(function ()
            {
                element[0].focus();
            });



        }
    };
}])

<input ng-model="your.value" focus-me-now />

postLinking에서 데코 레이팅 된 요소에 집중하도록하는 지시문을 만들 수 있습니다.

angular.module('directives')
.directive('autoFocus', function() {
    return {
        restrict: 'AC',
        link: function(_scope, _element) {
            _element[0].focus();
        }
    };
});

그런 다음 HTML에서 :

<input type="text" name="first" auto-focus/> <!-- this will get the focus -->
<input type="text" name="second"/>

이것은 postLinking이 HTML 처리에서만 발생하기 때문에 ng-show가 아닌 ​​모달 및 ng-if 토글 요소에 대해 작동합니다.


Mark와 Blesh는 훌륭한 답변을 가지고 있습니다. 그러나 Mark 's에는 Blesh가 지적하는 결함이 있습니다 (구현하기가 복잡하다는 것 외에도), Blesh의 대답은 실제로 필요한 모든 것이 방법이었을 때 특히 프론트 엔드에 초점 요청을 보내는 서비스를 만드는 데 의미 론적 오류가 있다고 생각합니다. 모든 지시문이 수신 할 때까지 이벤트를 지연합니다.

그래서 여기에 Blesh의 답변에서 많은 것을 훔치지 만 컨트롤러 이벤트와 "로드 후"서비스의 의미를 별도로 유지하는 작업이 끝났습니다.

이를 통해 컨트롤러 이벤트는 특정 요소에 초점을 맞추는 것 이외의 다른 항목에 쉽게 연결될 수 있으며 필요한 경우에만 "로드 후"기능의 오버 헤드를 발생시킬 수 있습니다. 이는 많은 경우에 해당되지 않을 수 있습니다.

용법

<input type="text" focus-on="controllerEvent"/>
app.controller('MyCtrl', function($scope, afterLoad) {
  function notifyControllerEvent() {
      $scope.$broadcast('controllerEvent');
  }

  afterLoad(notifyControllerEvent);
});

출처

app.directive('focusOn', function() {
   return function(scope, elem, attr) {
      scope.$on(attr.focusOn, function(e, name) {
        elem[0].focus();
      });
   };
});

app.factory('afterLoad', function ($rootScope, $timeout) {
  return function(func) {
    $timeout(func);
  }
});

이것은 또한 사용할 수 있습니다 ngModelController. 1.6 이상으로 작업 (이전 버전에서는 알 수 없음).

HTML

<form name="myForm">
    <input type="text" name="myText" ng-model="myText">
</form>

JS

$scope.myForm.myText.$$element.focus();

-

NB : 컨텍스트에 따라 타임 아웃 기능으로 래핑해야 할 수도 있습니다.

NB² :를 사용할 때 controllerAs거의 동일합니다. 그냥 교체 name="myForm"name="vm.myForm", 그리고 JS에서 vm.myForm.myText.$$element.focus();.


아마도 ES6 시대에서 가장 간단한 해결책 일 것입니다.

다음 하나의 라이너 지시문을 추가하면 HTML 'autofocus'속성이 Angular.js에서 효과적입니다.

.directive('autofocus', ($timeout) => ({link: (_, e) => $timeout(() => e[0].focus())}))

이제 다음과 같은 HTML5 자동 초점 구문을 사용할 수 있습니다.

<input type="text" autofocus>

여기 초보자이지만 다음 지시문 을 사용하여 ui.bootstrap.modal 에서 작동하도록 만들 수있었습니다 .

directives.directive('focus', function($timeout) {
    return {
        link : function(scope, element) {
            scope.$watch('idToFocus', function(value) {
                if (value === element[0].id) {
                    $timeout(function() {
                        element[0].focus();
                    });
                }
            });
        }
    };
});

그리고 $ modal.open 메서드에서 포커스를 놓아야하는 요소를 나타 내기 위해 다음을 사용했습니다.

var d = $modal.open({
        controller : function($scope, $modalInstance) {
            ...
            $scope.idToFocus = "cancelaAteste";
    }
        ...
    });

템플릿에 다음이 있습니다.

<input id="myInputId" focus />

다음 지시문은 나를 위해 트릭을했습니다. 입력에 동일한 자동 초점 html 속성을 사용하십시오.

.directive('autofocus', [function () {
    return {
        require : 'ngModel',
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.focus();
        }
    };
}])

modalInstance를 사용하고 객체가있는 경우 "then"을 사용하여 모달을 연 후 작업을 수행 할 수 있습니다. modalInstance를 사용하지 않고 모달을 열도록 하드 코딩 된 경우 이벤트를 사용할 수 있습니다. $ timeout은 좋은 해결책이 아닙니다.

할 수 있습니다 (Bootstrap3) :

$("#" + modalId).on("shown.bs.modal", function() {
    angular.element("[name='name']").focus();
});

modalInstance에서 모달을 연 후 코드를 실행하는 방법에 대한 라이브러리를 볼 수 있습니다.

$ timeout을 이와 같이 사용하지 마십시오. $ timeout은 0, 1, 10, 30, 50, 200 이상이 될 수 있으며 이는 클라이언트 컴퓨터와 모달을 여는 프로세스에 따라 다릅니다.

$ timeout을 사용하지 마십시오.

이 도움이 되길 바랍니다! :)


원하는 포커스 요소가 지시문 템플릿에 삽입되면 이전 답변이 모두 작동하지 않습니다. 다음 지시문은 단순 요소 또는 지시문 주입 요소 모두에 적합합니다 ( typescript 에서 작성했습니다 ). 내부 포커스 가능 요소에 대한 선택기를 허용합니다. self 요소에만 집중해야하는 경우-선택기 매개 변수를 지시문에 보내지 마십시오.

module APP.Directives {

export class FocusOnLoadDirective implements ng.IDirective {
    priority = 0;
    restrict = 'A';

    constructor(private $interval:any, private $timeout:any) {

    }

    link = (scope:ng.IScope, element:JQuery, attrs:any) => {
        var _self = this;
        var intervalId:number = 0;


        var clearInterval = function () {
            if (intervalId != 0) {
                _self.$interval.cancel(intervalId);
                intervalId = 0;
            }
        };

        _self.$timeout(function(){

                intervalId = _self.$interval(function () {
                    let focusableElement = null;
                    if (attrs.focusOnLoad != '') {
                        focusableElement = element.find(attrs.focusOnLoad);
                    }
                    else {
                        focusableElement = element;
                    }
                    console.debug('focusOnLoad directive: trying to focus');
                    focusableElement.focus();
                    if (document.activeElement === focusableElement[0]) {
                        clearInterval();
                    }
                }, 100);

                scope.$on('$destroy', function () {
                    // Make sure that the interval is destroyed too
                    clearInterval();
                });

        });
    };

    public static factory = ():ng.IDirectiveFactory => {
        let directive = ($interval:any, $timeout:any) => new FocusOnLoadDirective($interval, $timeout);
        directive.$inject = ['$interval', '$timeout'];
        return directive;
    };
}

angular.module('common').directive('focusOnLoad', FocusOnLoadDirective.factory());

}

간단한 요소의 사용 예 :

<button tabindex="0" focus-on-load />

내부 요소에 대한 사용 예 (일반적으로 템플릿이있는 지시문과 같은 동적 주입 요소) :

<my-directive focus-on-load="input" />

"입력"대신 모든 jQuery 선택기를 사용할 수 있습니다.


Mark Rajcok의 focusMe 지시문을 편집하여 하나의 요소에서 다중 초점 작업을 수행합니다.

HTML :

<input  focus-me="myInputFocus"  type="text">

AngularJs 컨트롤러에서 :

$scope.myInputFocus= true;

AngulaJS 지시어 :

app.directive('focusMe', function ($timeout, $parse) {
    return {
        link: function (scope, element, attrs) {
            var model = $parse(attrs.focusMe);
            scope.$watch(model, function (value) {
                if (value === true) {
                    $timeout(function () {
                        scope.$apply(model.assign(scope, false));
                        element[0].focus();
                    }, 30);
                }
            });
        }
    };
});

나는 더 나은 해결책을 찾고 그것을 찾지 않고 대신 그것을 만들어야하는 후에이 토론에 기여하고 싶다.

기준 : 1. 솔루션은 재사용 성을 높이기 위해 상위 컨트롤러 범위와 독립적이어야합니다. 2. $ watch를 사용하여 일부 조건을 모니터링하지 마십시오. 둘 다 느리고 다이제스트 루프의 크기가 증가하며 테스트가 더 어려워집니다. 3. 다이제스트 루프를 트리거하기 위해 $ timeout 또는 $ scope. $ apply ()를 사용하지 마십시오. 4. 입력 요소는 Directive가 열린 요소 내에 존재합니다.

이것이 내가 가장 좋아하는 솔루션입니다.

지령:

.directive('focusInput', [ function () {
    return {
        scope: {},
        restrict: 'A',
        compile: function(elem, attr) {
            elem.bind('click', function() {
                elem.find('input').focus();                
            });
        }        
    };
}]);

HTML :

 <div focus-input>
     <input/>
 </div>

나는 이것이 누군가를 도울 수 있기를 바랍니다!


간단 해요 .. 이거 먹어봐

HTML

<select id="ddl00">  
 <option>"test 01"</option>  
</select>

자바 스크립트

document.getElementById("ddl00").focus();

특정 요소에 초점을 맞추고 싶다면 아래 접근 방식을 사용할 수 있습니다.

  1. 라는 서비스를 만듭니다 focus.

    angular.module('application')
    .factory('focus', function ($timeout, $window) {
        return function (id) {
            $timeout(function () {
                var element = $window.document.getElementById(id);
                if (element)
                    element.focus();
            });
        };
    });
    
  2. 호출하려는 위치에서 컨트롤러에 주입하십시오.

  3. 이 서비스에 전화하십시오.


지시가 불필요하다고 생각합니다. HTML id 및 클래스 속성을 사용하여 필요한 요소를 선택하고 서비스에서 document.getElementById 또는 document.querySelector를 사용하여 포커스 (또는 jQuery와 동등한 항목)를 적용하도록합니다.

마크 업은 선택을 위해 추가 된 ID / 클래스가있는 표준 HTML / 각도 지시문입니다.

<input id="myInput" type="text" ng-model="myInputModel" />

컨트롤러 브로드 캐스트 이벤트

$scope.$emit('ui:focus', '#myInput');

UI 서비스에서 querySelector를 사용합니다-여러 일치 항목이있는 경우 (예 : 클래스로 인해) 첫 번째 항목 만 반환합니다.

$rootScope.$on('ui:focus', function($event, selector){
  var elem = document.querySelector(selector);
  if (elem) {
    elem.focus();
  }
});

$ timeout ()을 사용하여 다이제스트주기를 강제 할 수 있습니다.


그냥 커피를 좀 던지세요.

app.directive 'ngAltFocus', ->
    restrict: 'A'
    scope: ngAltFocus: '='
    link: (scope, el, attrs) ->
        scope.$watch 'ngAltFocus', (nv) -> el[0].focus() if nv

참고 URL : https://stackoverflow.com/questions/14833326/how-to-set-focus-on-input-field

반응형