Home > Software design >  how to use $sce in Angular directive
how to use $sce in Angular directive

Time:04-20

Basically we would like to sanitize html data as soon I used $sce it does not work is there any alternate option to use instead $sce ?

app.directive('stack', ['$timeout', function($timeout) {

    return {
      restrict: 'A',
      controller: 'StackController',
      scope: {
        onReady: '&?',
        onChange: '&',
        onDragStart: '&',
        onDragStop: '&',
        onResizeStart: '&',
        onResizeStop: '&',
        options: '='
      },
      link: function(scope, element, attrs, controller, $sce) {
  
        var stack = controller.init(element, scope.options);
       
        var serializeItems = function() {
          const data = [];
  
          $(element).children().each((index, item) => {
            const $item = $($sce.trustAsHtml(item)).data('_stack');
  
            data.push({
              id: $item.id,
              type: $($sce.trustAsHtml(item)).attr('type'),
              position: [
                $item.x,
                $item.y,
              ],
              size: [
                $item.width,
                $item.height,
              ],
            });
          });
  
          return data;
        }
  
      }
    };
  
  }]);

Thank in advance please guide

CodePudding user response:

Your injecting $sce in the wrong way:

app.directive('stack', ['$sce', function($sce){
    return {
        restrict: 'C',
        link: function (scope, element, attrs) {
            ...$sce(your content) ...
        }
    }
 }]);

Notice that the module should be injected to the directive, as opposed to being injected to the link function.

CodePudding user response:

I would use $sce with a wrapping function, just to render stuff in the View/HTML, so, in the controller:

scope.trustAsHtml(str) {
   return $sce.trustAsHtml(str);
}

in the view/html:

<div>{{trustAsHtml(yourData)</div>
  • Related