AngularJS+Protractor:如何获取嵌套ng-repeat标签的内容
如何用Protractor获取嵌套ng-repeat表格的元素
作为Protractor新手,处理嵌套ng-repeat确实容易懵,不过别担心,我们可以通过Protractor的by.repeater定位器结合层级遍历的方式来搞定这个表格。
先看你的HTML结构:
<table> <tr ng-repeat="row in rowcolumnsetup" id="{{$index}}"> <td ng-repeat="column in rowcolumnsetup" id="{{$index}}" ng-style="getClass($parent.$index,$index)"></td> </tr> </table>
这里外层tr用row in rowcolumnsetup循环生成行,内层td用column in rowcolumnsetup循环生成列(注:这里内层循环如果是column in row可能更符合表格数据逻辑,但我们按你给出的代码来处理)。
方法1:定位特定行和列的元素
如果你需要获取某一个具体单元格(比如第3行第2列,索引从0开始),可以这样写:
// 先定位目标行,再在该行内定位目标列 const targetRow = element(by.repeater('row in rowcolumnsetup').row(2)); // 第3行,索引为2 const targetCell = targetRow.element(by.repeater('column in rowcolumnsetup').row(1)); // 第2列,索引为1 // 获取单元格的id属性(对应列的$index值) targetCell.getAttribute('id').then(id => { console.log(`目标单元格的id是:${id}`); }); // 获取ng-style应用的样式(比如背景色) targetCell.getCssValue('background-color').then(color => { console.log(`目标单元格的背景色:${color}`); });
方法2:遍历所有行和列
如果你需要批量检查所有单元格的属性或样式,可以用each方法遍历行和列:
element.all(by.repeater('row in rowcolumnsetup')).each((rowElement, rowIndex) => { console.log(`正在处理第${rowIndex + 1}行`); // 在当前行内遍历所有列 rowElement.all(by.repeater('column in rowcolumnsetup')).each((colElement, colIndex) => { // 获取单元格的id colElement.getAttribute('id').then(colId => { console.log(`行${rowIndex},列${colIndex}的id:${colId}`); }); // 验证getClass方法返回的样式是否符合预期(可结合你的targetByRow数组做断言) colElement.getCssValue('background-color').then(color => { // 示例断言:expect(color).toEqual(yourExpectedColor); }); }); });
小提示
- 注意td的
ng-style里$parent.$index代表外层tr的索引(行号),td自身的$index是列号,你可以通过这两个值关联你的targetByRow数组,验证每个单元格的样式是否符合预期。 - 如果你的内层循环实际是
column in row(更符合表格数据绑定逻辑),只需要把代码里的column in rowcolumnsetup改成column in row即可。
内容的提问来源于stack exchange,提问作者ndNextLearn
相关产品推荐
相关产品推荐

