簡體   English   中英

在角度指令中將焦點設置為textarea

[英]set focus to textarea in an angular directive

我有一個實現就地編輯的指令。 在其link功能中,我有一只手表,應該在打開編輯時將焦點放在文本框上:

$scope.$watch('view.enabled', function(value) {
  if (value) {
    var element = $element.find('input') || $element.find('textarea');
    var input = element && element[0];
    if (input) {
      $timeout(function() {
        input.focus()
      });
    }
  }
});

指令可以根據參數實例化input元素或textarea 問題在於,在textarea元素上調用focus()不會為其設置焦點。 對於input元素,它確實設置了焦點。

這是plnkr。 請幫忙。

柱塞鏈接

編輯:在HTML的textarea上使用autofocus屬性可以使它獲得焦點,但是我仍然不明白為什么我不能以編程方式做到這一點。

我認為$ timeout不是將元素聚焦於創建的好方法。 您可以拆分“鏈接”屬性,可以拆分為“前置”和“后置”,用於前置鏈接和后置鏈接功能。

工作示例: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

您沒有將焦點設置在textarea上 嘗試這個:

if (input) {
    $timeout(function() {
        console.log(input);
        input.focus();
    });
}

它會給你這個:

<input ng-show="editableType !== 'multi-line'" 
       ng-model="view.value" 
       class="ng-pristine ng-valid ng-hide">

而不是文本區域 快速修復(僅適用於textarea )可能是:

var element = $element.find('textarea');

根據事物的順序,我不確定這是否有幫助:

var element = $element.find('textarea') || $element.find('input');

必須仔細看看...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM