Angular parse/evaluate/execute JS 由第 3 方 JS 加载到指令模板中

Angular parse/evaluate/execute JS loaded into directive template by 3rd Party JS

我搜索了 hi 和 lo,但找不到适合我的特定情况的 post relevant/helpful。

我有一个加载各种小部件的应用程序,其中一些加载包含需要执行的第 3 方 JS 的 JSONP。

我已经能够在小部件元素(指令模板)中加载 JS,但是,我不知道如何让 JS 实际执行。

我考虑过也许在编译时这样做,但我是新手所以不确定这是否是正确的方法。我尝试使用 eval() 但这没有用。我尝试了 .$digest 和 .$apply 但这也没有用。我只需要让 JS 执行,就好像我把它放在 HTML 中一样,没有任何 Angular。当我通过基本 jquery/HTML 页面执行此操作时,它按预期工作。

相关代码如下:

angular.module('protoApp')
.directive('thirdPartyWidget',['$http',function($http){
    return {
        restrict: 'E',
        scope: {},
        template: '<div id="myWidget"></div>',
        replace: true,
        link: function($scope, $el, $attrs){
            $http({
                method: 'JSONP',
                responseType: 'jsonp',
                url: $scope.url,
                data: thirdPartyWidgetProperties
            })
            .then(function(response){

                // this will properly insert JS into my $el
                // but this JS will not do anything/run.
                $el.append(response.data.html);
            });
        }
    }
}]);

(我知道我应该在这里直接使用服务而不是 $http,但我只是想让它尽可能简单地工作。)

例如,其中一个 JS 脚本用于 Google 分析。我期待在 JSONP 加载到 $el 之后,应该有一个对 GA 的请求,就像在非 AngularJS 版本中一样。

当我检查 DOM 时,我可以看到脚本确实被附加到 $el 中,但它没有 运行 或做它应该做的事情。它就在那里:

<div class="ng-isolate-scope"><div id="remoteProfiles"></div><script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-99999-99', 'website_name.com');
    ga('send', 'pageview');
</script>
<script type="text/javascript">...3rd party widget stuff...</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.1/require.min.js"></script>
<!--<script src="//requirejs.org/docs/release/2.1.11/comments/require.js"></script>--></div>

所以,看,它就在那里。我怎样才能真正做到 运行?

任何信息、建议、posts,任何你能指出我的东西都将不胜感激。

所以,我让这个工作的唯一方法基本上是将所有初始化 JS 完全放在 Angular 之外。它加载的代码非常糟糕。它加载 require 并执行许多 Angular 只是做鬼脸的 requireJS 事情。它加载 HTML 与 JS 逻辑,以便它被所有站点封装。 Angular 被脚本标签噎住了,不想处理任何一个。

我确实有一个版本,其中所有代码都在 index.html 文件中,我的指令中只有一个 div 和一个 ID。这很难看,我想继续看下去。

使用此 post (AngularJS: How to make angular load script inside ng-include?) and this directive (https://gist.github.com/subudeepak/9617483#file-angular-loadscript-js),我能够将我的所有脚本加载到指令的模板中。我确实必须创建几个全局变量($document 和 $window 没有让它们对我的模板中的脚本可用),但它比只将所有内容都放在 index.html 文件中要干净得多.如果指令从未加载,我的额外脚本也不会加载。

我确实放弃了指令周围的所有东西,只是接受它并将其直接合并到我现有的体系结构中(已经有一个用于此类事情的模块,并且不需要闭包)。