How can you access AngularJS scope using Playwright after migrating from Protractor?

I'm encountering a minor (hopefully) issue. For personal reasons, I need to transition from using Protractor to Playwright. Initially, everything was smooth sailing as I migrated numerous steps without any hitches. However, I've hit a roadblock while trying to migrate Protractor's code that involves executeScript() and accessing scope.

Here is an example of what I had in Protractor:

browser.executeScript(element => $(element).scope().$ctrl.myFunction(), finder.getWebElement());

In Playwright, I attempted the following (including console.log for debugging purposes):

const elementHandle: ElementHandle | null = await this.button.elementHandle();

await this.page.evaluate(
({ element, functionName }) => {
                    const angularElement = (window as any).angular.element(element);
                    const scope = angularElement.scope();
                    console.log("📣📣📣", scope); // returns undefined
                    console.log("📣📣📣",scope.$ctrl); // also returns undefined
                    scope.$ctrl[myFunction]();
                },
                { element: elementHandle, functionName }
            );

I'm completely bewildered by this challenge. I can't seem to figure out how to make it work. Any help would be greatly appreciated! Thank you in advance!

Answer â„–1

Finally uncovered the solution!

I discovered that in Angular, accessing scope requires being in debug mode. To achieve this using Playwright, I created a specific method and executed it within Cucumber's "Before" Hook:

async activateDebugMode() {
        // Defining a promise to resolve upon page reload
        const pageReloaded = new Promise((resolve) => {
            this.mainWindow.once("load", resolve);
        });

        // Verifying if AngularJS is loaded before enabling debug mode
        await this.mainWindow.evaluate(() => {
            if ((window as any).angular) {
                (window as any).angular.reloadWithDebugInfo();
            }
        });

        // Waiting for full page load
        await pageReloaded;

        // Checking if debug mode is now enabled
        const isDebugModeEnabled = await this.mainWindow.evaluate(() => {
            const bodyClasses = document.body.className.split(" ");
            return bodyClasses.includes("ng-scope");
        });

        // Including this for debugging purposes
        console.log("Is Debug Mode Enabled:", isDebugModeEnabled);
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Access basePath within the Next.js AppRouter

Is there a way to access the basePath in Next.js 13 when using AppRouter? To retrieve it, we can simply get router.basePath through the useRouter hook of PageRouter by importing `import { useRouter } from 'next/router' I am currently unable to ...

Traversing an array of objects in TypeScript and appending to a separate array if not already present

I have been given an array containing objects in the following format: export interface Part { workOrder?: string; task?: string; partNumber?: string; qty?: number; image?: string; name?: string; } My goal is to loop through each object in th ...

The variable 'this' is not recognized within the foreach loop

While working on my TypeScript code and iterating through an array, I encountered an issue with accessing the 'this' object. Here's a snippet of the code: console.log('before iterate, this = ' +this); myarray.days.forEach(function ...

Displaying JSON data in HTML using Angular

If you have a straightforward controller: controller: function($scope, $http){ $http.get(templateSource+'/object.customer') .then(function(result){ $scope = result.data; }); } The content of my object.customer file is a ...

What is the best way to send ServerSideProps to a different page in Next.js using TypeScript?

import type { NextPage } from 'next' import Head from 'next/head' import Feed from './components/Feed'; import News from './components/News'; import Link from 'next/link'; import axios from 'axios&apo ...

Tips for generating click event with Angular directive

I am completely new to AngularJs directive creation. I have created a directive where, when the user clicks on the delete button, I am trying to print the values of scope, element, and attrs in the console. However, nothing is getting printed. The json dat ...

Having trouble with your UI Router states not updating correctly when changing the URL in your Angular UI Router?

I have tried numerous solutions and tutorials already with no success in finding the right answer. Therefore, I am posting here in hopes of receiving a fresh perspective and a little challenge. Using: angular ui router The Issue I have set up differen ...

Why is it that HTML is not being shown?

Within my angular application, I have data that may contain line breaks, links, and other elements that need to be converted to HTML. To handle this requirement, I created a function that converts the text to HTML: $scope.textToHTML = function(text){ ...

Is requesting transclusion in an Angular directive necessary?

An issue has cropped up below and I'm struggling to figure out the reason behind it. Any suggestions? html, <button ng-click="loadForm()">Load Directive Form</button> <div data-my-form></div> angular, app.directive(&apos ...

Experiencing significant delays in keyboard response when using an Angular application on mobile browsers such as Safari

Experiencing a frustrating delay in keyboard response when using an Angular app on mobile Safari and Chrome. Surprisingly, there are no such issues when typing on desktop browsers. Any suggestions for troubleshooting this problem? My hunch is that it may ...

What is the best way to dynamically add the 'required' attribute to an input field?

My responsibility was to dynamically add required fields to all elements on each state that the user selected as required. In my database, I have a table containing the input ID (each input has a unique ID) and a boolean field indicating whether or not a r ...

Craft a unique typings file tailored to your needs

After recently creating my first published npm package named "Foo", I encountered some difficulties while trying to consume it in a TypeScript project. The tutorials on how to declare modules with custom typings were not clear enough for me. Here are the k ...

Achieving successful CSRF integration with Express.js, AngularJS, and Ngin

Having difficulty understanding how to set up csrf protection in my specific setup. My configuration includes nginx for serving static files, expressjs for handling API calls, and angularjs for the front end. All requests to /api/* are routed to express, w ...

What method does AngularJS use to distinguish between these two properties?

I grasp the concept that ng-model generates a property that corresponds to the {{name}}. How does AngularJS distinguish between the {{name}} derived from the ng-model and the {{name}} originating from the ng-repeat/ng-init? <section class="section"> ...

The process of invoking a function within another function in TypeScript Angular

Just starting out with Angular 2, I've written the following code in my Angular project: export class TestClass { constructor() { this.initMap(); } initMap() { this.marker.addListener('dragend', this.onMarkerDr ...

Deactivate an entire row in the MUI DataGrid

My task involves organizing the data into columns: const columns: GridColDef[] = [ { field: "firstName", headerName: "First name", width: 150, editable: true, }, { field: "lastName", headerName: & ...

AngularJS: Error message stating that '$scope is undefined'

Encountering '$scope is not defined' console errors in this AngularJS controller code: angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Au ...

I am continuously receiving the message "Alert: It is important for every child in a list to possess a distinct "key" prop." while working with the <option> list

Having trouble generating unique keys for my elements. I've tried different values and even Math.random() but still can't seem to get it right. I know the key should also be added to the outer element, but in this case, I'm not sure which on ...

What are some techniques for monitoring an Angular promise chain with Jasmine?

Incorporating AngularJS, CoffeeScript, and Jasmine within WebStorm, my goal is to conduct unit testing on a chain of promises. Imagine having the subsequent example service: Angular Service class ExampleService stepData: [] constructor: (@$http) ...

What could be causing my project to install an erroneous Angular version?

It appears that my project is not utilizing the latest Angular code, but I am unsure of the reason behind this. I have checked my package.json file and found the following dependencies: "devDependencies": { "@angular/common": "2.0.0", "@angular ...