4

Here's a jsfiddle showing the problem: http://jsfiddle.net/yRLKe/5/

One button compiles before injecting to the DOM, the other one injects before compiling. I did both to make sure that how I compile wasn't the cause of the problem.

Whichever button you click, check the console output and you'll see that the actual template's contents are not available when selecting from the DOM.

So the question is firstly why? - why does it behave this way? but most importantly how? - how can I get access to the actual loaded template's HTML via DOM selectors?

Here's the template:

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

Here's the controller:

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');  
  };
});

Here's the directive:

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());
    });    
  }
});

This directive outputs "test1" to the console whereas I would expect it to output "Hello Superman!".

4

2 回答 2

1

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

//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)

这是小提琴

另外,请参阅此答案并查看其中的链接。

于 2013-07-06T21:17:18.483 回答
0

compileBeforeInsert绝对不能工作,因为你正在调用 compile -> link -> element 但对返回的元素什么都不做。这是一个无操作。

至于为什么compileAfterInsert不起作用,我相信 ng-include 始终是异步的,即使内容已经在本地可用。这就是 rgillsetTimeout工作的原因。

您可能想重新考虑这种方法...... Angular 的想法是它不断地编译和消化,直到事情最终处于稳定的最终状态。并且在该路径中可能存在异步中断。

于 2013-07-06T22:04:42.553 回答