2

I am trying to understand how $sce and ngSanitize work so I can utilize it properly, please bare with a few questions I have for clarifications. I couldn't get enough details from the documentation.

First of all, what I understand $sce provides an escaping service for inputs which is enabled automatically?

  1. So does that man I do not need to explicitly use $sce? Are $scope variables in controllers automatically escaped. Or do I need to explicitly call $sce.trustAs/ParseAs ?

  2. Does this apply to Directives?

Example is the following directive safe:

link: function(scope, elm, attrs, ctrl) {
                // view -> model
                elm.on('blur keyup change', function() {
                    scope.$apply(function() {
                        ctrl.$setViewValue(elm.html());
                    });
                });

                // model -> view
                ctrl.$render = function() {
                    elm.html(ctrl.$viewValue);
                };
            }

As for ngSanitize, it seems to be a module that automatically configures $sce sensible defaults, so maybe perhaps with ngSanitize module I do not need to use the $sce service explicitly?

  1. I also notice there is a $santize service from ngModule, how is this different form $sce?

  2. Does ngSanitize automatically cover directives?

If not then is the following code any safer:

link: function(scope, elm, attrs, ctrl) {
                // view -> model
                elm.on('blur keyup change', function() {
                    scope.$apply(function() {
                        ctrl.$setViewValue(elm.html());
                    });
                });

                // model -> view using sanitize
                ctrl.$render = function() {
                    elm.html($sanitize(ctrl.$viewValue));
                };
            }
iQ.
  • 3,811
  • 6
  • 38
  • 57

1 Answers1

0

As for directives, you could probably look into how "ng-bind-html" works:

var parsed = $parse(attr.ngBindHtml);
element.html($sce.getTrustedHtml(parsed(scope)) || '');

So I suppose $sce still has to be used explicitly in your custom directives.

Alan
  • 596
  • 5
  • 18