2014-03-25 34 views
1

我有一個實現就地編輯的指令。在其link功能我有一個設想,當編輯接通將焦點設置文本框的手錶:將焦點設置爲角度指令中的textarea

$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。請幫忙。

Plunker Link

編輯:使用autofocus屬性在HTML中textarea使它獲得焦點,但我還是不明白,爲什麼我不能做到這一點編程。

回答

1

您不要將焦點設置爲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的。 快速修復(用於textarea的唯一)可能是:

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

根據事物的秩序,我不知道這是否會幫助:

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

要仔細看在它...

+0

我覺得自己很蠢。當然是。 DOM中有兩個元素...需要檢查可見性或根據模式查找特定的標記名稱。謝謝! – akonsu

+0

@akonsu:一個誠實的錯誤;) – user13500

1

我不認爲$超時是一個很好的方式來關注創建元素。您可以將「鏈接」屬性拆分爲「前」和「後」,用於前鏈接和後鏈接功能。

Working Example: 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 /> 

Full AngularJS Directive Docs: https://docs.angularjs.org/api/ng/service/$compile