加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 我可以获得Angular元素的编译html吗?

发布时间:2020-12-17 07:54:16 所属栏目:安全 来源:网络整理
导读:我使用$compile服务编译了一个元素.如果我将它直接添加到DOM,它看起来很棒,并且所有绑定都是正确的.如果我想将该元素作为字符串,它会显示{{stuffHere}}而不是绑定.有没有办法在编译后获取元素的html? $templateCache.put('template','divdivdivspancontent
我使用$compile服务编译了一个元素.如果我将它直接添加到DOM,它看起来很棒,并且所有绑定都是正确的.如果我想将该元素作为字符串,它会显示{{stuffHere}}而不是绑定.有没有办法在编译后获取元素的html?
$templateCache.put('template','<div><div><div><span>content is {{content}}</span></div></div>   </div>');

$scope.content = 'Hello,World!';

var el = $compile($templateCache.get('template'))($scope);
$('body').append(el);

alert(el.html());

http://plnkr.co/edit/1sxvuyUZKbse862PieBa?p=preview

附加到正文的元素显示内容是Hello,World!

该提示显示< div>< div>< span ng-binding> {{content}}< / span>< / div>< / div>

我希望从警报中看到的是< div>< div>< span ng-binding> Hello World< / span>< / div>< / div>

问题是你过早地阅读元素的内容.如果你在读取时添加$timeout,它将是正确的:
angular.module('demo',[]);
angular.module('demo').controller('PopoverDemoCtrl',function($scope,$timeout,$compile,$templateCache) {
  $templateCache.put('template','<div><div><div><span>content is {{content}}</span></div></div></div>');

  $scope.content = 'Hello,World!';

  var el = $compile($templateCache.get('template'))($scope);
  $('body').append(el);
  $timeout(function() {
    console.log(el.html());
  },300);   // wait for a short while
});

Updated Plunker

为什么需要$timeout?

调用$compile方法后,它不会立即生效.这是由于$digest循环,因为它使用运行$digest循环所需的$scope来查看是否有任何影响$scope.content.这就是你必须设置$timeout的原因,你需要等到$digest周期完成才能实际更改元素的内容.你可以阅读更多关于这一切如何联系在一起here.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读