2015-02-11 83 views
2

我正在編寫一個角度指令來包裝某些自定義下拉列表的邏輯。我的指令有3個下拉菜單,其中任何一個都可以實際使用。Angular指令檢查是否在隔離範圍內設置了可選綁定

我的指令(精簡)看起來是這樣的:

app.directive('dropdowns', 
    ['$http', '$filter', ... 
    function($http, $filter, ...) { 
     return { 
      restrict: 'E', 
      templateUrl: '/Some_template', 
      scope: { 
       customer: '=?', 
       warehouse: '=?', 
       location: '=?', 
      link: function (scope, elm, attrs) { 

       //How do I tell if scope.customer is set to a binding? 
      } 
     } 
    }]); 

如何檢查下拉綁定是否真的綁定到其他變量?要清楚,我無法檢查變量是否真實,因爲未定義的值很好。例如,如果我的HTML看起來像這樣:

<dropdowns customer="customer" warehouse="warehouse"></dropdowns> 

如何判斷客戶和倉庫是否已設置,但位置不是?最終,我使用這些信息來顯示/隱藏相關的下拉菜單。我寧願只檢查這些綁定,而不是僅僅添加另外幾個綁定到我的隔離範圍。

回答

5

您可以使用attrs參數。 attrs參數將向您顯示元素所有屬性中的原始值(不同之處在於雙捲曲將首先解析其值)。

//create the dropdowns if the attribute was present 
if(attrs.customer){ /* create the dropdown */} 
if(attrs.warehouse){ /* create the dropdown */} 
if(attrs.location){ /* create the dropdown */} 

下面是一個顯示差異的jsfiddle。

https://jsfiddle.net/L2j4ecd8/

相關問題