我正在尝试编写一个指令,为表单中的字段发出所有 HTML - 包装 div、标签、输入等。对于某些字段,我想使用 Angular UI Bootstrap's "typeahead" directive .
我首先尝试在模板中使用 ng-attr-typeahead='{{myTypeahead}}'。我预计,在未设置“myTypeahead”的字段上,不会有“typeahead”属性的证据。相反,在指令处理期间,该属性以未定义的值出现在属性列表中,并且会调用 typeahead 指令并立即崩溃,因为其输入未定义。
然后我尝试使用像这样的后编译函数:
compile: function compile(tElement, tAttrs, transclude) {
return function postLink(scope, iElement, iAttrs, controller) {
if ( iAttrs.eiTypeahead !== undefined ) {
var me = $(iElement);
var input = $("input", me);
input.attr("typeahead", iAttrs.eiTypeahead);
$compile(input[0]);
}
}
}
这会将“typeahead”属性放在输入元素上,但不会调用 typeahead 指令。
我预计这可能是其他帖子的重复,但我没有搜索正确的单词来找到它。
最佳答案
当您向指令元素添加其他指令时,应从指令的 compile
函数添加这些指令,并且您可以从 postLink
函数编译指令元素,该函数从编译中返回。
代码
compile: function compile(tElement, tAttrs, transclude) {
if ( iAttrs.eiTypeahead !== undefined ) {
var me = $(iElement);
var input = $("input", me);
input.attr("typeahead", iAttrs.eiTypeahead);
}
return function postLink(scope, iElement, iAttrs, controller) {
$compile(input[0]);
}
}
您可以引用this answe r 以获得更好的解释
关于javascript - AngularJS : invoking optional nested directive on template sub-element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31078743/