【问题标题】:Can I get the compiled html of an Angular element?我可以获得 Angular 元素的编译后的 html 吗?
【发布时间】:2014-10-30 18:19:27
【问题描述】:

我已经使用 $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

附加到正文的元素显示content is Hello, World!

警报显示&lt;div&gt;&lt;div&gt;&lt;span ng-binding&gt;{{content}}&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;

我想从警报中看到&lt;div&gt;&lt;div&gt;&lt;span ng-binding&gt;Hello World&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;

【问题讨论】:

    标签: angularjs angularjs-compile


    【解决方案1】:

    问题是您过早地阅读元素的内容。如果您将$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 循环,因为它使用$scope,它需要运行$digest 循环以查看是否有任何影响$scope.content。这就是为什么您必须设置$timeout 的原因,您需要等到$digest 循环完成后,才能真正更改元素的内容。你可以阅读更多关于这一切是如何联系在一起的here

    【讨论】:

    • 我需要你的帮助。我也想要绑定后的数据。但我仍然在 ng-repeat 中得到 {{ xxxx.xxx }}。有什么解决办法吗?
    • @churnsolidet 你能澄清一下吗?我不确定你的意思。
    • 我从视图中获取了我的模板。 var table = document.getElementById('my-table').outerHTML; $templateCache.put('template', table);我把一切都像上面的答案。关键是当我让 ng-repeat 循环我的表的 td 时,我已经在视图中了。然后我只是通过 id 获取我的表。它没有给我渲染的表格,而是用 {{ xxxx.xxxx }} 代替。
    • 通过运行你的代码,我仍然得到这个"
      content is {{content}}
      " 在控制台日志中。我想要的只是控制台日志中的“
      content is Hello, World!
    猜你喜欢
    • 2021-10-11
    • 2023-03-15
    • 1970-01-01
    • 2011-05-31
    • 2019-07-18
    • 2022-07-19
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多