开发者社区> 问答> 正文

AngularJS $compile 获取字符串结果问题?报错

AngularJS 版本:1.3.4

var template = "<div>{{id}}</div>";

var scope = $rootScope.$new(true);
scope.id = '1';

var element = $compile(template)(scope);

var result = element[0].outerHTML;

console.log(result);

想要获取编译链接后的结果


<div>1</div>



但还是输出没编译链接过的原内容



<div>{{id}}</div>



在获取结果前执行$apply()能获取到我想要的结果,但会报错($digest already in progress )



var template = "<div>{{id}}</div>";

var scope = $rootScope.$new(true);
scope.id = '1';

var element = $compile(template)(scope);

scope.$apply(); // 能获取到想要的结果,但会报错

var result = element[0].outerHTML;

console.log(result);


有什么好的办法可以处理这个问题吗




展开
收起
爱吃鱼的程序员 2020-06-14 19:57:29 684 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB
    $timeout(function(){console.log(element[0].outerHTML);});




    这个我试过了,不管用...还是谢谢你了~!

    这样修改下代码,应该就不会报错了:

    if(!$rootScope.$$phase){scope.$apply()}



    但是不明白为什么要这么做?DOM元素的操作不应该放到driective中来处理吗?

    就是想编译$templateCache的内容,但是$interpolate无法编译ng-repeat等指令,只有$compile才能编译,现在已经放弃$compile这条路了.....$interpolate循环输出了...悲剧
    2020-06-15 10:55:23
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Angular从零到一 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载