2012-10-21 93 views
2

我想将属性的存在绑定到AngularJS中的变量。具体而言,​​为iframe。说我有$myCtrl.allowJavascript作为一个变量,我想做的事:AngularJS绑定属性存在

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

凡​​属性存在时allowJavascript == false,我想沙箱属性时allowJavascript == true消失。

AngularJS有这样的机制吗?

我能找到的最接近的东西是here,它基本上说“它只适用于某些属性” - 但不适用于沙箱。

+0

这是一个潜在的危险设计。只有当iframe被导航到时,沙箱属性才会生效。换句话说,这可能不会做你认为它的作用。 – user239558

回答

3

可重用性,你可以把它沿着这些通用行:

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

你会使用它像:

<iframe add-attr="{sandbox: allowJavaScript, someOtherAttr: someOtherVar}"> 
+0

必须在attrs.addAttr上进行评估,但它可行 – Chuck

3

如果您愿意,您可以为此创建自定义指令。

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

使用是这样的:

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

甚至

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

其中控制器会像

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

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

谢谢,那会很好。 – Chuck