使用 Angular 将字符串中的 HTML 隐蔽编码为输入字段的纯文本

Covert encoded HTML in string to plain text for Input Fields using Angular

我有一个用例,我们可以在 JSON 中包含“&#”字符。

Name: "Kenneth Hinsvark & Maurice McAlister"

Address: "555555 W. Canyon Dr # B212"

从数据库中提取字符串值。显然,这些值是使用 HTML 编码保存到数据库中的。我需要能够在没有 HTML 字符的 textField 中显示数据。

我的主要要求是将输入字段值转换为纯文本。

Name: <input type="text" ng-model="user.name" escape-to-plain-text></input>

Address: <input type="text" ng-model="user.address" escape-to-plain-text></input>

如何将输入值转换为纯文本?

使用 $sce 对我不起作用

$scope.user.name = $sce.trustAsHtml('555555 W. Canyon Dr &#35; B212');

工作代码示例:

http://jsfiddle.net/egrendon/xa8cseoc/12/

没错。所以你需要一些东西:

  1. ngSanitize 注入您的模块。
  2. 对要输出 $sce 结果的元素执行 ng-bind-html

我已经编辑了你的 fiddle here. - 最后一行输出正确的 # 字符

因为它输出 HTML,你需要获取内容并解析它们以将它们放入输入中。所以从这个意义上说,你最好只做一个匹配( ) 在文本值上查找 HTML 个实体。

ngSanitize 解决方案适用于显示字段,但不适用于 edit/input 字段。

我能够通过创建自定义指令来回答将 HTML 转换为输入字段中的纯文本的主要问题。解决方案发布在 js-fiddle

http://jsfiddle.net/egrendon/xa8cseoc/22/

var app = angular.module('myApp', ['ngSanitize']);

app.controller('LoginController', function ($scope, $sce) {
    // This object is fected from a DB. The data is stored DB this way....
    $scope.user = {
        name : "Kenneth Hinsvark &#38; Maurice McAlister",
        address : "555555 W. Canyon Dr &#35; B212"
    };

    $scope.sample = $sce.trustAsHtml('555555 W. Canyon Dr &#35; B212');
});

app.directive('escapeToPlainText', function () {
    return {
        require: 'ngModel',
        link : function(scope, element, attrs, ngModel) {

            scope.$watch(function(){return ngModel.$modelValue;}, function(newValue, oldValue){
                if (newValue && newValue.length > 0) {
                    var hasEncodedHTML = newValue.indexOf("&#") > -1;
                    if (hasEncodedHTML){
                        var encodedValue = newValue;
                        var decodedValue = decodeHTMLtoPlainText(encodedValue);

                        ngModel.$setViewValue(decodedValue);
                        ngModel.$render();
                        console.log(decodedValue);
                    }
                }
            }, true);


            function decodeHTMLtoPlainText(aValue) {
                var elem = document.createElement('div');
                elem.innerHTML = aValue;
                return elem.childNodes[0].nodeValue;
            }

        }
    }
});