Angular 异步添加的 dom 里面ng绑定和js不执行不加载

描述:api.js 里面的子页面加载,异步获取html后ng的方法和js方法都不能执行。
解释:angular不允许异步添加的html、js直接生效。需要$compile编译一下 js需要写directive指令重新执行

// ng compile
var el=$compile("HTML代码")(scope); element.append(el);

// 具体用法
// 子页面的html里面
<script type="text/javascript-lazy" ng-src="XXXX.JS"></script>
<script type="text/javascript-lazy" >
alert('111')
</script>
    
// 主页面的js部分的需要加入下面的指令
    $app.directive('script', function ($compile) {
        return {
            restrict: 'E',
            scope: false,
            link: function (scope, elem, attr) {

                if (attr.type === 'text/javascript-lazy' || elem.text().indexOf('childrenFunction.') > -1) {

                    if (attr.ngSrc) {
                        var script = document.createElement('script');
                        script.setAttribute('type', 'text/javascript');
                        script.setAttribute('src', attr.ngSrc);
                        document.body.appendChild(script);
                        return;
                    } else {
                        var code = elem.text();
                        var f = new Function(code);
                        f();
                    }

                }
            }
        };
    });
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容