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

前端之家收集整理的这篇文章主要介绍了angularjs – 为什么ng-include动态加载模板的内容不能通过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并查看其中的链接.

猜你在找的Angularjs相关文章