繁体   English   中英

使用Jquery处理html字符串(在Angular应用程序中用于所见即所得编辑器)

[英]Manipulate html string with Jquery ( in Angular application for wysiwyg editor )

我有一个所见即所得的编辑器,它使用$ scope.variable作为HTML的源。

现在,我需要将div插入HTML字符串的某些部分。 因此,我可以以编程方式在所见即所得中追加,添加,删除所示内容的其他部分。 但是我无法使操作起作用。

将东西插入dom应该简单吗? 但是在此示例中未附加任何内容:

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>

朋克:

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

您需要使用.container选择器并将html移出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> 

您可以使用模块ngSanitize来获取指令ngBindHtml来完成此操作。 使用Angular时,您不必直接操作DOM。 如果我有jQuery背景,请查看“ Thinging in AngularJS”?

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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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