2016-01-04 113 views
1

這個問題歸結爲需要在指令中獲取<textarea>元素的光標位置。總之,我需要在這方面工作。在AngularJs中獲取Textarea光標位置

var position = element.selectionStart; 

至少有5個問題的答案使用各種方法,例如, this one for angular,this one for some jQuery extension,enter link description here

我已經閱讀了所有內容,並決定嘗試獲取選擇開始對象。這是我的PLNKR。我不知道我做錯了什麼。注意 - 背景變化的內容是看我是否正在選擇正確的元素,就是我。這裏編輯是代碼片段失敗:

 link: function(scope, elem, attrs) { 
      var textArea = elem.find("#itemTextArea"); 
      textArea.bind('click', function() { 
       //This gets to undefined, even though selectionStart is a property of textarea* 
       scope.testValue = elem.selectionStart; 
      }); 
     }, 

* https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Property/selectionStart

附:點擊文本區域立即知道指令中發生了什麼。

回答

10

你正在尋找的語法是:

scope.testValue = textArea.prop("selectionStart"); 
+0

哇。我花了一天的時間來解決這個問題。我想這就是我不使用jQuery並識別它的原因。非常非常感謝你。接受一分鐘。 – VSO

+2

很高興我能幫助你。 – jbrown

2

這也似乎工作

scope.testValue = textarea的[0] .selectionStart;

+0

感謝您的回覆。接受jbrown的答案,因爲他是第一個。 – VSO