2013-10-21 54 views
0

所以我看過很多這樣的問題,還沒有找到一個似乎涵蓋了我想要做的事情。在Angular指令模板中使用自定義標籤屬性

我在一個指令中使用了一個模板來創建一個像搜索框那樣的奇特東西的自定義下拉菜單。爲此,我必須使用template;我不能只使用compileelement.replaceWith(如果我使用compileattrs參數,但是自定義模板不起作用,我可以使用此工作)。

所有我想要做的就是選擇取決於屬性在我的自定義標籤的內容選擇特定陣列:

HTML:<customdropdown useoptionset="first"></customdropdown>

JS:

angular.module('ui.bootstrap', []) 

.constant('customdropdownConfig', { 
    //bunch of properties here 
}) 

.directive('customdropdown ', ['$parse', 'customdropdownConfig', function ($compile, customdropdownConfig) { 
    return { 
     restrict: 'EA', 
     replace: true, 
     template: (function(conf) { 
      var optionset = //how can i access the useoptionset attribute here? 

      var options = //stuff involving useoptionset and conf 

      return '<select ui-select="customDropdown">' + options + '</select>'; 
     }(customdropdownConfig)) 
    }; 
}]) 

似乎對我來說這應該是一個非常常見和明顯的用例,但也許我錯過了Angular的工作原理。

回答

1

嘗試使模板更加簡單,然後使用鏈接功能將動態內容添加到<select>元素。

像這樣:

.directive('customdropdown ', ['$parse', 'customdropdownConfig', function ($compile, customdropdownConfig) { 
    return { 
     restrict: 'EA', 
     replace: true, 
     template: '<select ui-select="customDropdown"></select>', 
     link: function(scope, elem, attrs){ 
      var optionset = attrs.optionset; 
      var options = //stuff involving useoptionset and conf 
      elem.html(options); 
      $compile(elem.contents())(scope); 
     } 
    }; 
}]); 

這聽起來像你可能已經嘗試過這一點,但我不明白爲什麼它是行不通的。如果不這樣做,也許你可以給出更多的解釋,說明你到目前爲止所做的嘗試以及爲什麼它沒有奏效。

+0

可能是我無法得到它的工作原因是,我還是比較新的角度,並不確定如何使用模板和鏈接功能(看起來像我試圖將兩者的功能'template')。這是多麼令人驚訝你的例子單獨清除的東西 - 謝謝,我相信這將工作。明天我會拍這張照片。 – sgroves

+0

讓我知道,如果它的工作原理或如果你需要更多的澄清 – tennisgent

+0

工作得很好,謝謝! – sgroves

相關問題