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.

3
  • 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 Commented Jul 22, 2017 at 7:31
  • 1
    See this link - stackoverflow.com/questions/38330039/… Commented Jul 22, 2017 at 11:22
  • still I'm facing same issue, i cant place the text in cursor position Commented Jul 26, 2017 at 7:44

1 Answer 1

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();
    }

  });
 }
}
}])
Sign up to request clarification or add additional context in comments.

Comments

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.