0

I wanted to try to sanitize script using $sce in AngularJS.

//Controller

 angular.module('App')
 .controller('SketchCtrl', function ($scope, $location, $sce , http) {
    $scope.init = function () {
        var sketchId = $location.path().split("/:").pop();
        http.getSketch(sketchId);
    }
    $scope.sanitize = function (script) {
        if(script){
            return $sce.trustAsJs(script);
        }
    }
 });

// View

<script ng-bind="sanitize('{Here is a script I want to sanitize}}')"></script>

But I got an error like this.

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!

I know how to sanitize html but do you have any idea to sanitize script?

2 Answers 2

2

The error you mentioned normally occurs when you create a loop of changes over a property. For example, like when you watch for changes on a certain property and then change the value of that property on the listener. You shouldn't change objects/models during the render or otherwise it will force a new render.

Sign up to request clarification or add additional context in comments.

Comments

0

To add to existing answers,

Simplified, $sce.trustAsJs notifies AngularJS's $rootScope that something may have changed, which most likely causes ng-bind to reevaluate the expression, the expression is calling sanitize and calls $sce.trustAsJs causing this to happen over and over until a limit is reached where it stops, because something seems to be going wrong.

Generally, just don't put function calls in html bindings unless they do really simple things. The way you can avoid what you're running into is to ng-bind a variable that you update only outside of the scope digest chain.

What you could for example do here is add ng-init, which we know only runs once, to set a variable, and then make ng-bind reference it;

<script ng-init="script = sanitize('{Here is a script I want to sanitize}}')"
        ng-bind="script"></script>

You can also set script in the above example from a controller, just make sure you only call sanitize whenever the script changes or is initialized.

Also if you're trusting arbitrary JS that you want to run you, might as well keep it simple and use eval.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.