0

I have a wysiwyg editor that uses a $scope.variable as it source of HTML.

Now i need to insert divs into certain parts of the HTML string. So i can programmatically append, prepend, remove etc. parts of the shown content in the wysiwyg. But i can't get the manipulation to work.

Should be simple to insert things into the dom right? But nothing gets appended in this example:

JAVASCRIPT:

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

app.controller("ctrl", function($scope) {

  $scope.obj = {};

  // html string
  $scope.obj.htmlString = ' <div class="wrapper-div">wrapper div<div class="container">container div<div class="inner-div">inner div</div></div></div>';

  // element inserted into html string ( virtual dom )
  $($scope.obj.htmlString).find('.container').prepend('<b>text inserted into container div</b>');

  // insert the elements to dom
  angular.element('.insert-here').prepend($scope.obj.htmlString);

});

HTML:

<body ng-app="app" ng-controller="ctrl">
  {{ obj.htmlString }}
  <div class="insert-here">
  </div>
</body>

PLUNKER:

https://plnkr.co/edit/dCzQF6YYth5NFOTkVahy?p=preview

lowkey
  • 334
  • 1
  • 7
  • 17

2 Answers2

0

You need to use .container selector and get the html out of the DOM

var htmlString = ' <div class="wrapper-div">wrapper div<div class="container">container div<div class="inner-div">inner div</div></div></div>';
// element inserted into html string ( virtual dom )
var $html = $('<div>' + htmlString + '</div>').find('.container').prepend('<b>text inserted into container div</b>');
htmlString = $html.html();
alert(htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
jcubic
  • 61,973
  • 54
  • 229
  • 402
0

You can use the module ngSanitize to get the directive ngBindHtml to accomplish this. You should not have to manipulate the DOM directly when using Angular. Check out “Thinking in AngularJS” if I have a jQuery background?

var app = angular.module("app", ['ngSanitize']);
app.controller("ctrl", function($scope) {
    $scope.insertHere = "<b>text inserted into container div</b>"
}); 
<div class="insert-here" ng-bind-html="insertHere"></div>

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

app.controller("ctrl", function($scope) {
  $scope.insertHere = "<b>text inserted into container div</b>"
});
/* Styles go here */

.insert-here{
  border: 2px solid red;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-sanitize.min.js"></script>

<body ng-app="app" ng-controller="ctrl">
  {{ obj.htmlString }}

  <div class="wrapper-div">wrapper div
    <div class="container">container div
      <div class="inner-div">inner div</div>
    </div>
  </div>
  <div class="insert-here" ng-bind-html="insertHere">
  </div>
</body>
Community
  • 1
  • 1