2

I want to be able to capture the highlighted portion of a text/string from an input field using AngularJS. I'm not really sure of where to start in tackling this problem.

For example, I have a textarea:

<textarea ng-model="input" placeholder="type your input">

How would I be able to capture the parts of the text that the user has highlighted or selected using his/her mouse pointer?

1
  • what do you mean by capture? Commented Mar 6, 2017 at 9:46

2 Answers 2

3

You can create a directive that attaches to textarea and input elements events and monitors for the currently highlighted text. Something like

var app = angular.module('module', []);

app.controller('MainCtrl', function($scope) {
  $scope.selectedText = '';
  $scope.textSelected = function(text){
    $scope.selectedText = text;
    $scope.$apply();
    //alert(text);
  };
});

app.directive('inputFieldSelection', function(){
  return{
    restrict: 'A',
    scope:{
      onSelected: '='
    },
      link:function(scope, elem, attrs){
        elem.on('select', function(){ 
         var text = elem.val().substring(elem.prop('selectionStart'), 
              elem.prop('selectionEnd'));
          scope.onSelected(text); 
        });
        
        elem.on('blur', function(){ scope.onSelected('') });
        elem.on('keydown', function(){ scope.onSelected('')});
        elem.on('mousedown', function(){ scope.onSelected('')  });
      }
    }
  });
<!DOCTYPE html>
<html ng-app="module">

  <head>
    <script data-require="[email protected]" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="MainCtrl">

    <textarea input-field-selection on-selected="textSelected" type="text"></textarea>
          <p>{{selectedText}}</p>
    </div>
  </body>

</html>

Sign up to request clarification or add additional context in comments.

Comments

0

angular.element('[ng-model="YOUR_MODEL_NAME_HERE"]').prop('selectionStart');
angular.element('[ng-model="YOUR_MODEL_NAME_HERE"]').prop('selectionEnd');

You can make use of 'selectionStart' and 'selectionEnd' to get the selection range. Hope this helps

1 Comment

Please add Working snippet to the answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.