2016-01-04 115 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