GrailsLearner
GrailsLearner

Reputation: 525

How to get the selected value from textarea in angularjs

Hi i am working on an example to display values in the text area and below is the link of the plunkr: http://plnkr.co/edit/QgWKTRsC6TBeqbFf80fO?p=preview

<!DOCTYPE html>
<html>

<head>
     <script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js" 
type="text/javascript"></script>
     <script src="script.js"></script>
</head>

   <body ng-app="testApp" ng-controller="testController">
   <textarea ng-model="stringArray" ng-list="&#10;" ng-trim="false" 
   rows="10"> 
   </textarea>

  <div>
     {{stringArray}}
  </div>
 </body>

 </html>

// Code goes here

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

 testApp.controller('testController', function ($scope)
 {
      $scope.stringArray =
      [
       "First String",
       "Second String",
       "Third String"
      ];
   });

Now i would like to know how to get the selected value from the test area.If i select First String value from text area i should see only the First String value in the output.

Upvotes: 0

Views: 943

Answers (1)

brk
brk

Reputation: 50291

Use window.getSelection().toString(), this will give the selected text, Also note a separate $scope variable is used to display the text, because using stringArray will replace the original content.

In this case ng-mouseup event is used

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

testApp.controller('testController', function($scope) {
  $scope.stringArray = [
    "First String",
    "Second String",
    "Third String"
  ];


  $scope.getSelectedText = function() {
    $scope.selectedTextDisplay = window.getSelection().toString();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="testApp" ng-controller="testController">
  <textarea ng-mouseup='getSelectedText()' ng-model="stringArray" ng-list="&#10;" ng-trim="false" rows="10"></textarea>

  <div>
    {{selectedTextDisplay}}
  </div>
</body>

Upvotes: 1

Related Questions