创建angular指令以在创建html时重用代码解析错误

Creating angular directive to reuse code - parse error while creating html

本文关键字:创建 代码 错误 angular 指令 html      更新时间:2023-09-26

下面是我正在创建的控件的代码片段。这种控制在不同的地方使用,变量也不同。

我正试图编写一个指令来清理代码,但在{{}}附近插入值时出现解析错误。

新到棱角分明,无法确定我缺少的是什么。请帮忙。

轨迹编辑是另一个指令。

原始控制代码:

<div id="text-wrapper">
                    <div track-edit="true" id="Type1Desc_{{t1Card.id}}" class="textbody" ng-blur="SaveDesc('Type1Desc_'+t1Card.id,t1Card.Description,'Type1')">
                        <div>
                            <p><div spellcheck="true"  ng-bind-html="t1Card.OrigDescription|diff:t1Card.Description"></div></p>
                        </div>
                    </div>
                </div>

指令代码

app.directive('customEditor', function () {
    return {
        restrict: "E",
        scope: {
            fId: "@",
            idAppend: "@",
            className: "@",
            origVal: "@",
            currVal: "@"
        },
        replace: true,
        transclude: false
        template: ' <div id="text-wrapper"><div track-edit="true" id="{{idAppend}}_{{fId}}" ' +
        'class="{{className}}" ><div><p>' +
        '<div spellcheck="true"  ng-bind-html="{{origVal}}|diff:{{currVal}}"></div></p></div></div></div>',
        link: function (scope, element, attrs) {
        }
    }
});

Html指令后:

 <custom-editor fid="{{t1Card.id}}" idappend="Type1Desc" classname="textbody" ng-blur="SaveLineItemDesc('Type1Desc_'+t1Card.id,t1Card.Description,'Type1')" origVal="{{t1Card.OrigDescription}}" currVal="{{t1Card.Description}}">
 </custom-editor>

我认为你的错误在于这一部分:

fId: "@",
idAppend: "@",
className: "@",
origVal: "@",
currVal: "@"

应该是:

fid: "@",
idappend: "@",
classname: "@",
origVal: "@",
currVal: "@"

在指令中:

<custom-editor fid="{{t1Card.id}}" idappend="Type1Desc" classname="textbody" ng-blur="SaveLineItemDesc('Type1Desc_'+t1Card.id,t1Card.Description,'Type1')" origVal="{{t1Card.OrigDescription}}" currVal="{{t1Card.Description}}">
 </custom-editor>

您有idappend,但您指的是idappend。这是错误的。您应该将其称为idappend。这同样适用于fid类名,它们应该指没有camelcase格式的情况

编辑代码-

如果您信任origValcurrValvalue,则替换以下语句:

ng-bind-html="{{origVal}}|diff:{{currVal}}"

有了这个

ng-bind-html-unsafe="{{origVal}}|diff:{{currVal}}"

或者你可以像这个一样使用$sce

$sce.parseAsHtml(your_data_value)

要了解更多信息,您也可以参考这篇文章。删除了ng-bind-html unsafe后,如何注入html?