Get Textarea Cursor Position in AngularJs

十年热恋 提交于 2019-12-20 05:02:41

问题


This question boils down to needing to get the cursor position of a <textarea> element in a directive. In short, all I need to work in this.

var position = element.selectionStart;

There are at least 5 answers on the subject using various methods, e.g. this one for angular, this one for some jQuery extension, enter link description here.

I have read them all and decided to just try to get the selection start object. Here is my PLNKR. I have no idea what I am doing wrong. Note - the background change stuff is to see whether or not I am selecting the right element, which I am. Edit here is a snippet of the code that fails:

      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

P.S. Click on text area to immediately know what's happening in directive.


回答1:


The syntax you are looking for is:

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



回答2:


This also seems to work

scope.testValue = textArea[0].selectionStart;



来源:https://stackoverflow.com/questions/34600231/get-textarea-cursor-position-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!