1

Here is something what I am trying to do

$sce.trustAsHtml('<span ng-class="getIconColor('+ myColor +')">')

which in my HTML code just prints

<span ng-class="red">

But I am expecting ng-class attribute to be evaluated before $sce returns it. Somewhat like this for my code to work

<span ng-class="red" class="red">

How can this be done?

acd10
  • 73
  • 11
  • Possible duplicate of [Accessing ng-click when rendered via $sce.trustAsHtml](https://stackoverflow.com/questions/41787478/accessing-ng-click-when-rendered-via-sce-trustashtml) – Kaustubh Khare Nov 23 '17 at 10:42
  • 1
    Why don't you use `$sce.trustAsHtml('')` directly? – Kaustubh Khare Nov 23 '17 at 10:42
  • Yeah. That is one work around I figured out. But there were couple of other directives also, like tooltips and I cannot use this method in all cases. I was kinda looking for a more generalized solution. – acd10 Nov 23 '17 at 11:41
  • Then you can use the custom directive to achieve this. – Kaustubh Khare Nov 23 '17 at 12:12

2 Answers2

1

it's a compilation issue, $sce service doesn't work out of the box when you render dynamic content that needs compilation. you can resolve this by creating your own directive that force a compile.

app.directive('dynamic', function ($compile) {
      return {
        restrict: 'A',
        replace: true,
        link: function (scope, ele, attrs) {
          scope.$watch(attrs.dynamic, function(html) {
            ele.html(html);
            $compile(ele.contents())(scope);
          });
        }
      };
    })

    $scope.trustedContent = function(){
      return $sce.trustAsHtml('<span ng-class="getIconColor('+ myColor +')">');
    }

<div ng-bind-html="trustedContent()" dynamic> </div>

Rendering directives within $sce.trustAsHtml

http://plnkr.co/edit/3CewDscih8diAo4mMSwJ?p=preview

Karim
  • 8,454
  • 3
  • 25
  • 33
0

Solution1:-

In This case, angularjs doesn't compile. Angulajs does not understand about new directive is added and he has execute it. To run case you need to compile your HTML.So Angularjs will understand that and it will give your expected output.

To achieve this you need to create directive, which will do compilation of HTML code.

Solution2:-

Instead of this you can directly use $sce.trustAsHtml('<span class="getIconColor('+ myColor +')">');

Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48