javascript - AngularJS : invoking optional nested directive on template sub-element

标签 javascript angularjs dom angularjs-directive angularjs-compile

我正在尝试编写一个指令,为表单中的字段发出所有 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/

相关文章:

javascript - JQuery .load 需要重新加载

javascript - Windows 8 中的 float WinJS.UI.ListView 元素 - HTML 应用程序

javascript - 在选择中使用 ngPluralize

javascript - 测试 Angular $emit 和 $on 事件

javascript - Jquery - 获取子元素的最快方法

javascript - 为什么 firstChild 不返回第一个元素?

javascript - 在javascript dom中,是否有tagName到HTMLElement的映射?

javascript - 使用数组的值更改 div 的背景 url

javascript - 提取任意给定数组中的所有数字,然后将它们全部加在一起。

javascript - D3JS 的 AngularJS 指令是否存在?