Search code examples
javascriptjqueryhtmlangularjscontenteditable

Insert div or custom-directive in contenteditable div at cursor position in angularjs


I have to insert a custom directive in my contenteditable div.

   /*Editor Div*/
      <div id="edBody"  contenteditable="true"></div>
   /*Insert one custom directive*/
   <a ng-click="insertType('fibtext')">Add Directive</a>

I tried this:

  <input type="button" value="Insert" ng-click="addHtmlAtCaret('<dc-tags></dc-tags>')">
   /* Directive */
    asignmentApp.directive('dcTags', function() {
       return {
          restrict: 'E',
          template: 'new <b> Value </b>'
       };
    });

Please help me. Fiddle:- http://jsfiddle.net/k2SUJ/1/

Here's a fiddle demo which i tried.


Solution

  • In order for Angular to be aware of your added element and do its magic, you need to $compile the element and link it to a scope.

    So you'll need a controller with a scope. You also need to replace the onclick handlers with ng-click and also $compile the element:

    In HTML:

    <input type="button" value="..." ng-click="addHtmlAtCaret(...)">
    

    In JS:

    app.controller('ctrl', function ($compile, $scope) {
        $scope.addHtmlAtCaret = function (html) {
            document.getElementById('test').focus();
            ...
            var el = document.createElement("div");
            el.innerHTML = html;
            $compile(el)($scope);
            ...
        };
    });
    

    See, also, this short demo.