angularjs指令不返回带有element.html(“string”)的jquery对象

时间:2014-11-19 19:43:21

标签: jquery angularjs-directive

我在指令中有以下代码:

compile: function compile(scope, element, attributes) {
            return {
                pre: function preLink(scope, element, attributes) {
            },
            post: function postLink(scope, element, attributes) {
                if (directive.template == '') {
                    var template = getTemplate(scope.field.type);
                    element.html(template).show();
                    $compile(element.contents())(scope);
                }
            }
        }
    }

它有80%的时间都有效。但有时候,我得到一个错误,说undefined不是一个函数。

我已经完成了调试(使用console.logs,因为如果我有调试控制台,则不会发生这种情况),而且它抱怨“show”未定义。

我认为,因为html(htmlString)返回一个jQuery对象,有时会失败并返回null

我的代码有问题吗?或者,有没有办法捕获错误并再次触发链接功能,或者我可以使我的代码工作的任何其他方式?

[编辑1]

我失败后能够调试一次。 element.html(htmlString)中的返回对象是 JQLite [1]

当指令有效时,它会返回 x.fn.x.init [1]

老实说,我不知道AngularJS足以理解这一点,但它可能是一个线索

[编辑2]

我仍然不明白根本原因,也就是说,为什么有时候元素是JQLite,有时候是x.fn.x.init,但我意识到我不需要 show()< / strong>,所以我的代码结束了

                    var template = getTemplate(scope.field.type);
                    element.html(template);
                    $compile(element.contents())(scope);

并且有效

1 个答案:

答案 0 :(得分:0)

当尚未加载jQuery时会发生此问题。

它似乎只有80%的时间失败的原因是,在其他所有时间你都会慢慢地使用那个编译函数,从而给jQuery加载时间。

要修复,只需在加载角度的脚本之前放置加载jQuery的脚本。这将在您的html中,但根据您的构建设置,您可能只需要重新排序 bower.json 文件。