2012-10-21 36 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