您可以在您的指令中定義角度應該如何處理該屬性值。
這意味着,如果你定義它像這樣它會被解析爲普通的javascript:
scope: {
closeOthers: '='
}
//gives you in scope.closeOthers:
<e close-others="true" /> //true
<e close-others="'someText'" /> //someText
<e close-others="variableName" /> //contentOfVariableName
你真正想要的是將它解析爲字符串屬性(字符串嵌入插值表達式)是這樣的:
scope: {
closeOthers: '@'
}
//gives you in scope.closeOthers:
<e close-others="true" /> //true
<e close-others="'someText'" /> //'someText'
<e close-others="variableName" /> //variableName
<e close-others="prefix/{{variableName}}" /> //prefix/contentOfVariableName
scope: {}
創建一個新的隔離範圍。我個人不喜歡那些孤立作用域和希望創建一個正常的範圍子與scope: true
和觀看或分析我自己的屬性值:
.directive('e', ['$interpolate', function($interpolate) {
return {
restrict: 'E',
scope: true,
link: function(scope, element, attributes) {
attributes.$observe('closeOthers', function(value) {
if ('true' === value.toLowerCase()) {
// ...
}
});
//or if you don't need a watcher, which I prefer sometimes, because it's not always needed and costs performance
var value = $interpolate(attributes.closeOthers)(scope.$parent);
if ('true' === value.toLowerCase()) {
///...
}
}
}
});
你說I want this attribute to always be true, so I do not need a scope variable for this
,所以我想你甚至都不需要解析它(如果你不關心{{}}表達式)。然後,你可以簡單地做:
link: function(scope, element, attributes) {
var closeOthers = 'closeOthers' in attributes; //true or false
}
,它允許您使用「近距離別人是這樣的:
<accordion close-others></accordion>
<accordion close-others="true"></accordion>
應該可以正常工作,你有它的方式,如果沒有創建演示是不是做如預期的那樣 – charlietfl 2014-09-06 14:16:54
如何在使用布爾值true和和名爲true的變量之間進行切換? Angular首先檢查是否存在一個名爲true的變量,如果不是,則將其視爲值? – EricC 2014-09-06 14:21:01
哦,我剛剛意識到,可能不允許調用變量「true」...對於這個愚蠢的問題抱歉! – EricC 2014-09-06 14:23:10