2013-10-21 60 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

相关问题