AngularJS:调用模板子元素上的可选嵌套指令

AngularJS : invoking optional nested directive on template sub-element

本文关键字:嵌套 指令 元素 调用 AngularJS      更新时间:2023-09-26

我正试图编写一个指令,为表单中的字段发出所有HTML——包装div、标签、输入等。对于某些字段,我想使用Angular UI Bootstrap的"typeahead"指令。

我第一次尝试在模板中使用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]);
    }
}

您可以参考这个答案r来更好地解释