2

I want to bind the presence of an attribute to a variable in AngularJS. Specifically, sandbox for an iframe. Say I have $myCtrl.allowJavascript as a variable, I want to do:

<iframe src="..." sandbox />

Where the sandbox attribute is present when allowJavascript == false, and I want the sandbox attribute to disappear when allowJavascript == true.

Does AngularJS have a mechanism for this?

The closest thing I could find was here, which basically says "it will just work for certain attributes"--but not for sandbox.

1
  • This is a potentially dangerous design. The sandbox attribute only takes effect when the iframe is navigated to. In other words, this might not do what you think it does. Commented Oct 24, 2013 at 11:50

2 Answers 2

3

For reusability you could make it generic along these lines:

app.directive("addAttr", function() {
  return function(scope, element, attrs) {
    scope.$watch(attrs.addAttr, function(addAttr) {
      for (var key in addAttr) {
        if (addAttr[key]) element.attr(key, true);
        else element.removeAttr(key);
      }
    }
  }
}

You'd use it like:

<iframe add-attr="{sandbox: allowJavaScript, someOtherAttr: someOtherVar}">
Sign up to request clarification or add additional context in comments.

Comments

3

You could create a custom directive for this if you wanted to.

app.directive('sandboxIf', function() {
  return {
        restrict: 'A',
        link: function(scope, elem, attr, ctrl) {
            /* eval whatever was passed to sandbox-if="" 
               to see if it's true or false. */
            if(scope.$eval(attr.sandboxIf)) {
                elem.attr('sandbox','sandbox'); //sandbox="sandbox"
            }else{
                elem.removeAttr('sandbox');
            }
        }
    };
});

use would be like:

<iframe sandbox-if="foo"></iframe>

or even

<iframe sandbox-if="test()"></iframe>

where the controller would be like

app.controller('MyCtrl', function($scope) {
   $scope.foo = true;

   $scope.test = function() {
       return true;
   };
});

1 Comment

Thank you, that'll do just fine.

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.