如何在将 html 保存到数据库时转义?

How to escape html while saving it to db?

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

main.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>

filter.js

angular
  .module('riskAssessmentApp', [
    'ngSanitize'
  ])
  .filter('escapeHtml', function ($sce) {
    // Modified by Rockallite: Add $sce.trustAsHtml() to mute "Error: $sce:unsafe"
    // 
    // 
    // 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];
      }));
    }
  });

app.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"
    // 
    // 
    // 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];
      }));
    }
  });