Chuck
Chuck

Reputation: 656

AngularJS Bind Attribute Presence

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.

Upvotes: 2

Views: 823

Answers (2)

Tim Stewart
Tim Stewart

Reputation: 759

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}">

Upvotes: 3

Ben Lesh
Ben Lesh

Reputation: 108501

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;
   };
});

Upvotes: 3

Related Questions