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

angularjs – 为什么ng-include动态加载模板的内容不能通过DOM选

发布时间:2020-12-17 16:58:59 所属栏目:安全 来源:网络整理
导读:这是一个显示问题的jsfiddle: http://jsfiddle.net/yRLKe/5/ 一个按钮在注入DOM之前编译,另一个按钮在编译之前注入.我做了两件事,以确保我编译的方式不是问题的原因. 无论您单击哪个按钮,请检查控制台输出,您将看到从DOM中选择时实际模板的内容不可用. 所以
这是一个显示问题的jsfiddle: http://jsfiddle.net/yRLKe/5/

一个按钮在注入DOM之前编译,另一个按钮在编译之前注入.我做了两件事,以确保我编译的方式不是问题的原因.

无论您单击哪个按钮,请检查控制台输出,您将看到从DOM中选择时实际模板的内容不可用.

所以问题首先是为什么? – 为什么它会这样?
但最重要的是如何? – 如何通过DOM选择器访问实际加载的模板的HTML?

这是模板:

<script type="text/ng-template" id="template1.html">
   <div>This is template 1!</div>
   <div id="test">Hello {{name}}</div>
</script>

这是控制器:

myApp.controller('MyCtrl',function($scope) {
  $scope.name = 'Superhero';
  $scope.template = {url:'template1.html'};
  $scope.clickButton1 = function(){
    $scope.$emit('buttonClicked1');  
  };
  $scope.clickButton2 = function(){
    $scope.$emit('buttonClicked2');  
  };
});

这是指令:

myApp.directive('compileBeforeInsert',function($compile){
  return function(scope,element,attrs){
    scope.$on('buttonClicked1',function(ev){
        var container = $('#container');
        container.html('<div ng-include src="template.url" id="template">test1</div>');
        $compile(container)(scope);
        console.log('before');
        console.log($('#template').html());
    });    
  }
});

该指令将“test1”输出到控制台,而我希望它输出“Hello Superman!”.

解决方法

将输出写入控制台时,不会呈现dom.使用$timeout,您可以查看呈现的内容.很多人说这是一个黑客.无论如何,它的确有效.这是我改变的内容,两个指令的结果相同:

//after injecting $timeout in the directive:
  $compile(container)(scope);
  console.log('before');
  console.log($('#template').children().text());
  $timeout(function(){
      console.log('before,in timeout:');
      console.log($('#template').children().text());
  },0)

Here’s the fiddle

另外,see this answer并查看其中的链接.

(编辑:李大同)

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

    推荐文章
      热点阅读