【问题标题】:how can i load javascript file along with ng-include template我如何加载 javascript 文件以及 ng-include 模板
【发布时间】:2013-12-03 22:25:05
【问题描述】:

我正在使用下面的代码在我的主文件中包含一个模板。

<p ng-include=" 'activity.html' "></p>

我的activity.html是这样的,

<script type="text/javascript" src="myjsfile.js"></script>

<p>Activity page contents</p>

但 javascript 没有与模板一起加载

我在 SO 中发现了一些与此相关的问题,但找不到有效的解决方案。 答案之一是在主文件中的 angularjs 上方加载 jquery,以便脚本标签被接受。但没有发现它工作。

【问题讨论】:

    标签: javascript jquery angularjs


    【解决方案1】:

    我在这里找到了这个答案load script inside ng-include,不幸的是它不是那里接受的答案。所以我在这里为它提供了一些更新以满足需要。

    库链接here

    创建一个包含以下脚本的js文件并加载到主文件中。

    (function (ng) {
        'use strict';
    
        var app = ng.module('ngLoadScript', []);
    
        app.directive('script', function() {
            return {
                restrict: 'E',
                scope: false,
                link: function(scope, elem, attr) {
                    if (attr.type=='text/javascript-lazy') {
                        var code = elem.text();
                        var f = new Function(code);
                        f();
                    }
                }
            };
        });
    }(angular));
    

    并且,加载 ngLoadScript 模块作为应用依赖:

    angular.module('myApp', [
        'ngLoadScript'
    ])
    

    在部分 (**activity.html) 中使用text/javascript-lazy 作为type 属性值,而不是script 标记,而不是text/javascript:**

    <script type="text/javascript-lazy">
        alert("Yup!");
    </script>
    

    加载外部 js 还需要做一些工作:

    我使用ddrive 中的以下代码来加载脚本(在 ma​​in.html 中)

    function loadjscssfile(filename, filetype) {
        if (filetype == "js") {
            // if filename is a external JavaScript file
            var fileref = document.createElement('script');
            fileref.setAttribute("type","text/javascript");
            fileref.setAttribute("src", filename);
        }
        else if (filetype == "css") {
            //if filename is an external CSS file
            var fileref = document.createElement("link");
            fileref.setAttribute("rel", "stylesheet");
            fileref.setAttribute("type", "text/css")
            fileref.setAttribute("href", filename)
        }
        if (typeof fileref != "undefined") {
            document.getElementsByTagName("head")[0].appendChild(fileref)
        }
    }
    

    和部分(activity.html):

    <script type="text/javascript-lazy">
        loadjscssfile("myjsfile.js", "js");
    </script>
    

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 2014-08-19
      • 2019-12-08
      相关资源
      最近更新 更多