【问题标题】:LazyLoading angular directives延迟加载角度指令
【发布时间】:2014-12-18 11:46:46
【问题描述】:

我在使用 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 蜜蜂:

(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

【问题讨论】:

    标签: angularjs lazy-loading


    【解决方案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);
                    })
        });
    

    【讨论】:

      猜你喜欢
      • 2016-06-13
      • 1970-01-01
      • 1970-01-01
      • 2017-12-05
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多