延迟加载角度指令

时间:2014-12-18 11:46:47

标签: angularjs lazy-loading

我在使用ocLazyLoad延迟加载一个简单的指令时遇到了问题。代码是:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://code.jquery.com/jquery-1.11.2.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.js"></script>
    <script src="ocLazyLoad.js"></script>
</head>
<body>
    <div id="example" ng-app="LazyLoadTest" ng-controller="TestController">
        <say-hello to="world"></say-hello>
    </div>
    <script>
        angular.module("LazyLoadTest", [ "oc.lazyLoad"])
            .controller("TestController", function($scope, $ocLazyLoad){
                $ocLazyLoad.load({
                        name: "testApp",
                        files: ["testApp.js"],
                        serie: true
                    }).then(function () {
                        var el = angular.element('#example');
                        el.append('<say-hello to="world"></say-hello>');
                    }, function (e) {
                        console.log(e);
                    })
        });
    </script>
</body>
</html>

使用testApp.js beeing:

(function () {
    'use strict';
    angular.module("testApp", []).directive("sayHello", function () {
        return {
            scope: {
                to: '@to'
            },
            restrict: "E",
            template: '<p>Hello {{to}}</>'
        };
    });
})();

该指令在没有延迟加载的情况下使用时不会显示任何内容。如你所见,我从一开始就在DOM中有一个指令,当然angularJS不会识别指令,因为模块还没有延迟加载,后来我用angular append函数添加它。我认为ocLazyLoad会使用新模块引导应用程序,因此指令将被解析。但事实似乎并非如此。在这个例子中,如何让指令与延迟加载一起使用。

我还创建了一个plunker

1 个答案:

答案 0 :(得分:1)

我发现了这个问题。我必须在追加之前编译元素。请参阅以下工作代码,其中编译函数在解析promise时运行:

    angular.module("LazyLoadTest", [ "oc.lazyLoad"])
        .controller("TestController", function($scope, $ocLazyLoad, $compile){
            $ocLazyLoad.load({
                    name: "testApp",
                    files: ["testApp.js"],
                    serie: true
                }).then(function () {
                    var el, elToAppend;
                    elToAppend = $compile('<say-hello to="world"></say-hello>')( $scope );
                    el = angular.element('#example');
                    el.append(elToAppend);
                }, function (e) {
                    console.log(e);
                })
    });
相关问题