2014-09-06 98 views
2

我想使用具有屬性的directive。我希望這個屬性總是爲真,所以我不需要一個範圍變量。但我確定以下是錯誤的,它可能是一個名爲true的範圍變量,而不是布爾值true。這應該怎麼寫我想要的?在指令屬性的html中使用值而不是變量

<accordion close-others="true"> 
</accordion> 

編輯:我意識到這是一個壞榜樣。如果我有一個屬性,我想給它賦值「someText」。我該如何區分值「someText」和某個名爲「someText」的變量?像這樣:

<some-directive some-attribute="someText"></some-directive> 
+0

應該可以正常工作,你有它的方式,如果沒有創建演示是不是做如預期的那樣 – charlietfl 2014-09-06 14:16:54

+0

如何在使用布爾值true和和名爲true的變量之間進行切換? Angular首先檢查是否存在一個名爲true的變量,如果不是,則將其視爲值? – EricC 2014-09-06 14:21:01

+0

哦,我剛剛意識到,可能不允許調用變量「true」...對於這個愚蠢的問題抱歉! – EricC 2014-09-06 14:23:10

回答

3

您可以在您的指令中定義角度應該如何處理該屬性值。

這意味着,如果你定義它像這樣它會被解析爲普通的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> 
+0

哇,這比我期待的要詳細得多,我從中學到了很多答案!非常感謝@MArc :) – EricC 2014-09-06 15:01:23

相關問題