简体   繁体   中英

angular js convert string to HTML and preview it in the page

I have String contains Some HTML tags
for example :

$scope.string = '<div> <span> some text </span> </div>';

I want to convert it to html element and do some changes
so I did That :

$scope.stringAfterEdit = angular.element($scope.string).find("span").addClass('newClass');

then I need to append my html to the page after edits .
so I tried this :

<div ng-bind-html="stringAfterEdit"></div>

but didn't work .
any idea how to do that ?
Thanks in advance.

You need to use $sce :

  $scope.string = '<div> <span class="newclass"> some text </span> </div>';

  $scope.trustedHtml = $sce.trustAsHtml($scope.string);

and here you cann add any classes from css. Like newClass

And then html:

<div ng-bind-html="trustedHtml"></div>

working plunker: http://plnkr.co/edit/JDEkkG9Wyg12LNXdmjDo?p=preview

I solved this by this way :
Note I'm using Jquery with angularJS

$scope.string = '<div> <span> some text </span> </div>';
$scope.stringAfterEdit = angular.element($scope.string);
$scope.container = angular.element('.content');
$scope.container.append($scope.stringAfterEdit);

and HTML

<div class="content"></div>

Try this:

  var string = '<div><span> some text </span> </div>';
  var ele = angular.element(string);
  ele.find("span").addClass('newClass');
  $scope.trustedHtml = $sce.trustAsHtml(ele.html());

html:

<div ng-bind-html="trustedHtml"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM