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

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

本文关键字:应用程序 用于 所见即所得 编辑器 Angular 操作 Jquery html 字符串 使用      更新时间:2023-09-26

我有一个所见即所得的编辑器,它使用$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 选择器并从 DOM 中获取 html

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。看看"Thinking in AngularJS",如果我有jQuery背景?

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>