更改$compile对象的 html 在 Angular 中失败

Changing the html of a $compile's object fails in Angular

本文关键字:Angular 失败 html compile 对象 更改      更新时间:2023-09-26

Angular 1.5:我有一个ng-repeat,它渲染的文本中有ng点击的html。工作正常。

这是我的编译指令:

app.controller('PageCtrl', pageController)
    .directive('compile', [
        '$compile', function($compile) {
            return function(scope, element, attrs) {
                scope.$watch(
                    function(scope) {
                        return scope.$eval(attrs.compile);
                    },
                    function(value) {
                        element.html(value);
                        $compile(element.contents())(scope);
                    }
                );
            };
        }
    ]);

这是我与编译指令的 html 绑定

<div  class="mt10" ng-repeat="row in aqdas.Notes  | filter: filterNotes">
    <span class="pull-left text-bold mr5">{{row.Number}}. </span>
      <div compile ng-bind-html="TrustDangerousSnippet(row.Text,'note')">
           {{row.Text}}    
    </div>
</div>

这是我的TrustDangerousSnippet(简化)

    $scope.TrustDangerousSnippet = function(text, kind) {
        var simpletext = new RegExp("(" + $scope.search + ")", "gi");
        text = text.replace(simpletext, "<mark>$1</mark>");
        var val = $sce.trustAsHtml(text);
        return val;
    };

问题:在 TrustDangerousSnippet 中,我使用 reg ex 来突出显示文本的一个区域。当我这样做时,编译不起作用。似乎当我更改要绑定的文本时,$compile不喜欢/允许它?

我怎样才能让$compile喜欢它,或者以其他方式突出显示文本?

也许是这个?

<div compile="TrustDangerousSnippet(row.Text, 'note')"></div>

指令需要参数。尝试这样并删除手表(执行一次编译),您可能会遇到摘要问题。

app.controller('PageCtrl', pageController)
.directive('compile', [
    '$compile', function($compile) {
        return function(scope, element, attrs) {
            var html = scope.$eval(attrs.compile);
            element.append($compile(html)(scope));
        };
    }
]);