ScreenshotNeo

BlogHow-to

How to Select AngularJS Options with Node Horseman

Use Node Horseman to select AngularJS options reliably: wait for dynamic ngOptions, choose the real value, verify ngModel, and troubleshoot failures.

By the ScreenshotNeo team30 September 20264 min read

How to Select AngularJS Options with Node Horseman

Use Horseman’s .select(selector, value) method, but wait until AngularJS has created the target <option> first. Then verify both the selected option and the application state that depends on it. AngularJS can generate options asynchronously with ngOptions, so selecting immediately after navigation often runs before the option exists.

1. Install and start Node Horseman

Node Horseman is a promise-based Node API for PhantomJS. PhantomJS must be available on your PATH, installed through a supported package, or supplied with the phantomPath option. Install Horseman in a project:

npm install node-horseman

If PhantomJS is not on your path, pass its executable explicitly when creating the instance:

const Horseman = require('node-horseman');

const horseman = new Horseman({
  phantomPath: '/absolute/path/to/phantomjs'
});

Use the path appropriate for your operating system and installation. Keep one Horseman instance per job and close it in a finally block so PhantomJS does not remain running.

2. The basic selection workflow

  1. Open the page.
  2. Wait for the <select> and the intended option.
  3. Call .select(selectSelector, optionValue).
  4. Verify the selected value and visible label.
  5. Verify the dependent result or other application state.
  6. Close Horseman.

The second argument is the option’s value attribute. It is not necessarily the text a user sees. Inspect the markup or read the option values before choosing one.

3. Complete runnable example

This example waits for AngularJS to render a specific option, selects it, and checks the resulting DOM. Replace the URL and selectors with those from your page.

const Horseman = require('node-horseman');

const URL = 'https://example.com/angular-form';
const SELECTOR = 'select[name="country"]';
const OPTION_VALUE = 'us';

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function waitForOption(horseman, selectSelector, value, timeoutMs = 15000) {
  const started = Date.now();

  while (Date.now() - started < timeoutMs) {
    const found = await horseman.evaluate((selector, wantedValue) => {
      const select = document.querySelector(selector);
      if (!select) return false;
      return Array.from(select.options).some(option => option.value === wantedValue);
    }, selectSelector, value);

    if (found) return;
    await sleep(250);
  }

  throw new Error(`Option ${value} did not appear within ${timeoutMs} ms`);
}

(async () => {
  const horseman = new Horseman();

  try {
    await horseman
      .open(URL)
      .waitForSelector(SELECTOR);

    await waitForOption(horseman, SELECTOR, OPTION_VALUE);

    await horseman.select(SELECTOR, OPTION_VALUE);

    const state = await horseman.evaluate((selector) => {
      const select = document.querySelector(selector);
      const option = select && select.options[select.selectedIndex];
      return {
        value: select ? select.value : null,
        label: option ? option.textContent.trim() : null
      };
    }, SELECTOR);

    if (state.value !== OPTION_VALUE) {
      throw new Error(`Expected ${OPTION_VALUE}, got ${state.value}`);
    }

    console.log('Selected option:', state);

    // Verify application-specific output. Adjust this selector and condition.
    await horseman.waitForSelector('[data-selection-result]');
    const result = await horseman.evaluate(() => {
      const element = document.querySelector('[data-selection-result]');
      return element ? element.textContent.trim() : null;
    });
    console.log('Dependent result:', result);
  } finally {
    await horseman.close();
  }
})();

4. Waiting for AngularJS options

.waitForSelector() waits for an element to exist and has a documented default timeout of 5,000 ms. Waiting only for the <select> is insufficient when ngOptions fills its options after an HTTP request. Wait for the actual option value, as the example does.

Wait for the option AngularJS creates, then select and verify the resulting state.
Wait for the option AngularJS creates, then select and verify the resulting state.

Wait for a known option with a CSS selector

await horseman
  .waitForSelector('select[name="country"]')
  .waitForSelector('select[name="country"] option[value="us"]')
  .select('select[name="country"]', 'us');

This works when AngularJS renders a normal value attribute. If the option value is generated or encoded by a directive, use an evaluate poll that inspects select.options.

Why a fixed delay is weaker

await horseman.waitFor(2000);

A delay can be shorter than a slow API response or much longer than necessary. It proves only that time passed, not that the desired option exists. Prefer an option-aware condition and retain a timeout so a broken page fails clearly.

5. Finding the correct selector and value

Use a stable selector such as a field name, ID, or dedicated test attribute. Avoid selectors tied to AngularJS-generated classes or changing DOM positions.

const details = await horseman.evaluate(() => {
  const select = document.querySelector('select[name="country"]');
  return select ? Array.from(select.options).map(option => ({
    value: option.value,
    label: option.textContent.trim(),
    disabled: option.disabled
  })) : [];
});
console.log(details);

Do not assume a visible label such as United States has us as its value. Select using the value, then verify the label.

6. AngularJS binding and dependent controls

AngularJS ngModel binds a select to a scope property. ngOptions can create option elements from an array or object expression. Selecting the DOM control should be followed by an application-level check because custom directives, watchers, and dependent widgets can behave differently.

The option value and the visible label can differ, so inspect both before asserting.
The option value and the visible label can differ, so inspect both before asserting.
<select name="country"
        ng-model="form.country"
        ng-options="country.code as country.name for country in countries">
</select>
<div data-selection-result>{{ form.country }}

For a dependent city field, verify that the city options changed after selecting the country:

await horseman.select('select[name="country"]', 'us');
await waitForOption(horseman, 'select[name="city"]', 'nyc');
await horseman.select('select[name="city"]', 'nyc');

If the application updates only after a custom event, inspect the page’s directive behavior and verify the visible result rather than assuming every AngularJS implementation reacts identically.

7. Reading and asserting the selected state

const selected = await horseman.evaluate((selector) => {
  const select = document.querySelector(selector);
  if (!select) return null;
  const option = select.options[select.selectedIndex];
  return {
    value: select.value,
    label: option ? option.textContent.trim() : null,
    index: select.selectedIndex
  };
}, 'select[name="country"]');

if (!selected || selected.value !== 'us') {
  throw new Error(`Selection failed: ${JSON.stringify(selected)}`);
}

For a real workflow, add a second assertion: a result panel appears, a dependent control contains expected options, or a submit-ready value is displayed. That catches cases where the browser value changed but the application model did not update as expected.

8. Common errors and fixes

Error or symptom Likely cause Fix
phantomjs: command not found PhantomJS is unavailable on PATH. Install a supported PhantomJS package or pass its absolute path with phantomPath.
waitForSelector times out on the select The selector is wrong, the page is inside a frame, or navigation failed. Inspect the rendered markup, confirm the URL, and account for the correct frame context.
The select exists but the option does not ngOptions is still loading data. Poll for the actual option value instead of sleeping for a fixed duration.
Selection returns the wrong item The visible label was used instead of the option value. Enumerate select.options and pass the exact value string.
Value changes but dependent UI does not A custom directive, watcher, or asynchronous request has not completed. Wait for the dependent result and assert its content; investigate page-specific event handling.
Option is disabled AngularJS has not enabled it yet or business rules disable it. Wait until it is enabled and verify option.disabled before selecting.
Works locally but fails in automation Timing, PhantomJS compatibility, or page features differ. Log the option list, use explicit readiness checks, and capture the final state for diagnosis.
Process remains after an error close() was skipped. Always close Horseman in finally.

9. Frames, redirects, and page readiness

A selector in an iframe is not present in the top-level document. Confirm where the AngularJS app is rendered before waiting. Redirects can also invalidate an early selector check, so wait after the final navigation state. If the page has a loading shell, wait for a stable application element and then for the target option.

10. Reliability and performance

  • Use condition-based waits. They finish as soon as the option is ready and avoid arbitrary long sleeps.
  • Set realistic timeouts. Keep a bounded timeout so an unavailable API or broken page produces a useful failure.
  • Reuse a browser only when appropriate. Reusing one instance can avoid startup overhead, but isolate jobs when cookies or application state could leak between runs.
  • Keep evaluations small. PhantomJS evaluate arguments and return values must be JSON-serializable; return strings, numbers, booleans, arrays, or plain objects rather than DOM nodes, closures, or functions.
  • Close every instance. This releases PhantomJS resources and prevents orphaned processes.

11. Debugging checklist

  • Can PhantomJS start from the same environment as Node?
  • Did the final URL load successfully?
  • Does the select selector match exactly one element?
  • What option values and labels exist at the moment of selection?
  • Is the target option enabled?
  • Does the selected value match the expected value after .select()?
  • Did the dependent AngularJS content update?
  • Does the script always call close()?

12. Or skip the browser setup

If your goal is to capture the resulting page rather than drive PhantomJS yourself, ScreenshotNeo provides a single screenshot API request. See the ScreenshotNeo API documentation for the available options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/angular-form -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com/angular-form"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com/angular-form' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server lets AI agents use take_screenshot, get_page_info, and capture_pdf. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

Create a free ScreenshotNeo account to get started.

13. FAQ

Does Horseman select by visible text?

.select(selector, value) selects by the option value. Read the option list if the label and value differ.

Should I wait for AngularJS itself?

Wait for the concrete option or dependent result your task needs. Framework presence alone does not prove that asynchronous data is ready.

Can I return a DOM node from evaluate?

No. Return JSON-serializable data such as a string, number, boolean, array, or plain object.

Is AngularJS still maintained?

Official AngularJS support ended in January 2022. Existing applications can still be automated, but plan migrations and runtime compatibility accordingly.

When should I verify more than the selected value?

Whenever selection triggers validation, network requests, dependent fields, or custom directives. Assert the visible application result as well as the DOM value.