首页 > 解决方案 > 如何获取 ng-repeat 的 ElementById 内容?

问题描述

如何获取 ng-repeat 的内容?

<div ng-repeat="w in quick.wint">
   <div id="wname"><strong>{{w.Name}}</strong></div>
   <div id="wcount">{{w.Count}} Open Queues</div>
</div>

我想将它们分配给变量以打印文档

var wname = document.getElementById('wname').innerHTML;
var wcount = document.getElementById('wcount').innerHTML;
var popupWin =window.open('','_blank','width=300,height=300');
popupWin.document.open();
popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()"><h1>Documentation</h1>' + wname + '</body></html>');
popupWin.document.close();

我想在文档上以不同于在浏览器中显示的方式对其进行格式化。例如,它在浏览器中显示为:

<wname>
<wcount>

我希望它在文档中显示为:

<wname> : <wcount>

提前致谢。

标签: javascriptangularjs

解决方案


您可以像这样在每个 id 上附加索引:

<div ng-repeat="w in quick.wint; let i = index">
   <div id="wname-{{i}}"><strong>{{w.Name}}</strong></div>
   <div id="wcount-{{i}}">{{w.Count}} Open Queues</div>
</div>

因此,如果您想获取特定行,您可以通过连接的 id 调用它:

var wname = document.getElementById('wname-1').innerHTML;
var wcount = document.getElementById('wcount-1').innerHTML;

但是如果你想要所有的内容,那么也许你应该使用一个类并使用 querySelectorAll - 来获取一个孩子的数组?

<div ng-repeat="w in quick.wint">
   <div class="wname"><strong>{{w.Name}}</strong></div>
   <div class="wcount">{{w.Count}} Open Queues</div>
</div>

const wnames = document.querySelectorAll(".wname")
const wcounts = document.querySelectorAll(".wcount")

https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll


推荐阅读