Angularjs directive for inserting text into textarea caret

I have a controller MyCtrland a directive myText. When the model in changes MyCtrl, I want to update the directive of the textareadirective myTextby inserting the text in the current position / carriage.

I tried to reuse the code from the Insert text in which the cursor uses Javascript / jquery

My code: http://plnkr.co/edit/WfucIVbls2eekL8kUp7e

Here is my HTML:

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link href="style.css" rel="stylesheet" />
    <script data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.js" data-require="angular.js@1.2.x"></script>
    <script src="app.js"></script>
  </head>

  <body>
    <div ng-controller="MyCtrl">
      <input ng-model="someInput">
      <button ng-click="add()">Add</button>
      <p ng-repeat="item in items">Created {{ item }}</p>  
    </div>

    <textarea my-text="">

    </textarea>

  </body>

</html>

JavaScript:

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

app.controller('MyCtrl', function($scope, $rootScope) {
  $scope.items = [];

  $scope.add = function() {
    $scope.items.push($scope.someInput);
    $rootScope.$broadcast('add', $scope.someInput);
  }
});

app.directive('myText', ['$rootScope', function($rootScope) {
  return {
    link: function(scope, element, attrs) {
      $rootScope.$on('add', function(e, val) {
        console.log('on add');
        console.log(val);

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

      });
    }
  }
}])

Now this does not work, because it is elementnot a DOM object. Here is the error:

TypeError: Object [object Object] has no method 'focus'

QUESTION: So my question is how to fix this? Or how to get a real DOM object from an angular element object?

+4
2

Try:

var domElement = element[0];

DEMO

+10

Short anwser:

element[0]

DOM.

:

angular.element jqLite, , jQuery. HTML.

link : scope, element, attrs ctrl.

element DOM, . , HTML.

, (?)

+5

Source: https://habr.com/ru/post/1524027/


All Articles