0

I want sample code to add a text to textarea angularjs code, can any one help.

Writing an SMS with some custom name field like {userName} #userName# etc. These are onclick events, when user clicks, respected text should be added in cursor position in textarea box.

Dovydas Šopa
  • 2,282
  • 8
  • 26
  • 34
veera
  • 31
  • 1
  • 4
  • Save custom text in a variable and place a `ng-model="myText"` to textbox, and onclick event bind a function, and in function, `$scope.myText = $scope.customMessage` – Wasif Khan Jul 22 '17 at 07:31
  • 1
    See this link - https://stackoverflow.com/questions/38330039/inserting-text-at-current-cursor-position-in-textarea-using-angularjs-ng-click – Denny John Jul 22 '17 at 11:22
  • still I'm facing same issue, i cant place the text in cursor position – veera Jul 26 '17 at 07:44

1 Answers1

0

Check this link and use the directive in your app http://plnkr.co/edit/Xx1SHwQI2t6ji31COneO?p=preview

app.directive('myText', ['$rootScope', function($rootScope) {
 return {
 link: function(scope, element, attrs) {
  $rootScope.$on('add', function(e, val) {
    var domElement = element[0];

    if (document.selection) {
      domElement.focus();
      var sel = document.selection.createRange();
      sel.text = val;
      domElement.focus();
    } else if (domElement.selectionStart || domElement.selectionStart === 0)           {
      var startPos = domElement.selectionStart;
      var endPos = domElement.selectionEnd;
      var scrollTop = domElement.scrollTop;
      domElement.value = domElement.value.substring(0, startPos) + val +        domElement.value.substring(endPos, domElement.value.length);
      domElement.focus();
      domElement.selectionStart = startPos + val.length;
      domElement.selectionEnd = startPos + val.length;
      domElement.scrollTop = scrollTop;
    } else {
      domElement.value += val;
      domElement.focus();
    }

  });
 }
}
}])