How to select elements using protractor created by

2019-06-26 19:49发布

问题:

I need to select the textbox created by ng-repeat and send some values using sendKeys Function. But I'am not sure about the method to select the textboxes. Please suggest a method to accomplish this Or Should I use css selectors instead.

<div class="qst_input_hld ng-scope" ng-repeat="option in options track by $index">
<input type="text" class="input-sm ng-pristine ng-valid" ng-model="options[$index]" placeholder="Option 1" ng-class="isOptionEmpty[$index] ? 'error-border' : ''">
<!-- ngIf: $index > 1 -->
</div>

回答1:

There are multiple ways to locate the text input and, since there is a repeater there, I suspect there are multiple text boxes. Assuming you want to send keys to the first one, here is one option:

var desiredInput = element.all(by.repeater("option in options")).first().all(by.tagName("input")).first();
desiredInput.sendKeys("desired text");

Note that you don't need to handle the track by part at all - it is getting stripped away by Protractor (source code reference).

Also note that I've just used the by.tagName() technique which may or may not work depending on if you have the other input elements there. You can be more strict and use a CSS selector instead, e.g. check the placeholder:

var desiredInput = element.all(by.repeater("option in options")).first().$('input[placeholder="Option 1"]');

And, if you want to send keys to input element for every item in the repeater, use each():

element.all(by.repeater("option in options")).each(function (elm) {
    var desiredInput = elm.$('input[placeholder="Option 1"]');
    desiredInput.sendKeys("desired text");
});


回答2:

Provide a name and id attribute to your text boxes :

<input ... name="your_textbox" id="textbox_{{index}}" />

And if you want to select all textboxes :

document.getElementsByName("your_textbox");

Specific textbox :

document.getElementById("textbox_"+i);   //i=index

Through Protractor : First change the ng-model of your input box to :

<input type="text" class="input-sm ng-pristine ng-valid" ng-model="option" placeholder="Option 1" ng-class="isOptionEmpty[$index] ? 'error-border' : ''"> <!-- see ng-model=option -->

Then select it by using model :

var repeaterElements= element(by.repeater('option in options'));

repeaterElements.each(function(entry) {
    var input = entry.element(by.model("option"));
});