如何在将 html 保存到数据库时对其进行转义

How to escape html while saving it to db?

本文关键字:转义 数据库 html 保存      更新时间:2023-09-26

我想在保存到数据库时转义特殊字符和html,我可以使用过滤器使用以下代码来完成该任务吗我收到错误您的模块未正确加载,我需要在app中添加依赖项吗.js。AngularJs 的新手任何帮助将不胜感激。

主.html

<textarea rows="2" class="form-control" id="name"
    ng-model="processDTO.processLongName"
    placeholder="Business Process Name" maxlength="1024" name="processName"
    required
    ng-bind-html="escapeHtml"
    data-tooltip-html-unsafe="<div>{{1024 - processDTO.processLongName.length}} characters left</div>"
    tooltip-trigger="{{{true: 'focus', false: 'never'}[processDTO.processLongName.length >= 0 || processDTO.processLongName.length == null ]}}"
    tooltip-placement="top" tooltip-class="bluefill">
</textarea>

过滤器.js

angular
  .module('riskAssessmentApp', [
    'ngSanitize'
  ])
  .filter('escapeHtml', function ($sce) {
    // Modified by Rockallite: Add $sce.trustAsHtml() to mute "Error: $sce:unsafe"
    // http://stackoverflow.com/a/32835368/2293304
    // http://stackoverflow.com/a/28537958/2293304
    // https://github.com/janl/mustache.js/blob/master/mustache.js#L82
    var entityMap = {
        "&": "&amp;",
        "<": "&lt;",
        ">": "&gt;",
        '"': '&quot;',
        "'": '&#39;',
        "/": '&#x2F;'
    };
    return function(str) {
      return $sce.trustAsHtml(String(str).replace(/[&<>"''/]/g, function (s) {
          return entityMap[s];
      }));
    }
  });

应用.js

angular.module('riskAssessmentApp', [
    'angularSpinner',
    'ngResource',
    'ui.router',
    'ngCookies',
    'bacMultiselect',
    'kendo.directives',
    'kendoMultiselectTreeview',
    'offClick',
    'myMaxlength',
    'requireControlPoint',
    'disableControlPoint',
    'disablePageElements',
    'progressStepbar',
    'ui.bootstrap',
    'orcit.ssoHandler',
    'orcit.icon',
    'orcit.multiselectTreeview',
    'orcit.loader'
    'ngSanitize'
]).config(function ($stateProvider, $httpProvider, $urlRouterProvider,$tooltipProvider) {

错误

[$injector:nomod] Module 'riskAssessmentApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

riskAssessmentApp模块定义两次。

在你的filter.js不要重新定义它,只需将过滤器附加到该模块:

angular.module('riskAssessmentApp')
  .filter('escapeHtml', function ($sce) {
    // Modified by Rockallite: Add $sce.trustAsHtml() to mute "Error: $sce:unsafe"
    // http://stackoverflow.com/a/32835368/2293304
    // http://stackoverflow.com/a/28537958/2293304
    // https://github.com/janl/mustache.js/blob/master/mustache.js#L82
    var entityMap = {
        "&": "&amp;",
        "<": "&lt;",
        ">": "&gt;",
        '"': '&quot;',
        "'": '&#39;',
        "/": '&#x2F;'
    };
    return function(str) {
      return $sce.trustAsHtml(String(str).replace(/[&<>"''/]/g, function (s) {
          return entityMap[s];
      }));
    }
  });