【问题标题】:Custom directive from jQuery not loaded correctly来自 jQuery 的自定义指令未正确加载
【发布时间】:2016-04-07 06:50:25
【问题描述】:

我正在尝试加载 -outside angular - 动态自定义指令 但是尽管我使用了$compile,但没有加载自定义指令 如下: 自定义指令是:

app.directive('mydirective',function (){
  return {
     template: '<div>Succeeded !</div>',
  }
})

这里是我动态加载指令的地方:

function showresultcust() {
angular.injector(['ng']).invoke(['$compile',
    function ($compile) {
        var scope = angular.element(document.getElementById("test1")).scope();
        var _html = '<div>{{name}}-</div><div mydirective >Not Succeed</div>';
        //var _html='<div >{{loaded}}</div>';
        var obj = $('#content');
        $('#content').html($compile(_html)(scope));
        // compile!!!
        $compile(obj.contents())(scope);
        scope.$digest();
        setTimeout(function () {
            scope.$apply();
        });
    }
]);
}

请注意,动态 HTML 中的 {{name}} 已正确加载,但自定义指令未正确加载。 完整的演示在this 'plnkr.co' link

如果您可以直接在上面的“plnkr”链接中进行更正,我将不胜感激。

【问题讨论】:

    标签: angularjs directive


    【解决方案1】:

    代码未编译mydirective 指令,因为它不是ng 模块的一部分。将包含该指令的模块添加到新注入器的依赖列表中。

    //NOT this   
    //angular.injector(['ng']).invoke(['$compile',
    
    //Do this
    angular.injector(['ng','tumblr']).invoke(['$compile',
        function ($compile) {
            var scope = angular.element(document.getElementById("test1")).scope();
            var _html='<div>{{name}}-</div><div mydirective >Not Succeed</div>';
            $('#content').html($compile(_html)(scope));
            scope.$apply();
        }
    ]);
    }
    

    angular.injector 函数总是创建一个新的注入器,它需要依赖列表中的所有依赖项。

    【讨论】:

    • 有效!谢谢@georgeawg,我刚刚将 tumblr 更改为实际名称 plunker
    • 请再问一个问题,当我使用 templateUrl 时,它再次没有翻译它显示的模板 {{name}} ,并且仅在以相同方式动态加载但在此处使用 templateUrl 示例:plnkr.co/edit/L82o3zVbM5p76Kyfp8WE?p=preview
    • 请注意,在我的示例中简化了编译和应用。您的 plnkr 有两个 $compiles 和一个原始 setTimeout。所有这些都是不必要的。
    • 感谢@georgeawg,我会更新它,如果我在这里使用 templateUrl 演示,请您帮忙解释一下:plnkr.co/edit/L82o3zVbM5p76Kyfp8WE?p=preview 翻译不正确?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多