Angular seems to be experiencing issues with maintaining context when executing a function reference for a base class method

Imagine we have CtrlOne that extends CtrlTwo, with a componentOne instantiated in the template of CtrlOne. Here is some code to illustrate the issue:

class CtrlOne extends CtrlTwo {
    constructor() { super(); }
}

class CtrlTwo {

    sayMyName(name: string) {
        console.log(this.getMyLastName() + name);
    }

    getMyLastName() {
       return 'squarepants';
    }  
}

This is the template associated with CtrlOne:

<component-one data-say-my-name="vm.sayMyName"></component-one>

And this is the stateless componentOne:

angular.module('mymodule').component('componentOne', {
     bindings: {
         sayMyName: '&'
     },
     template: '<button data-ng-click="$ctrl.sayMyName()('spongebob')></button>'
});

When clicked, the function sayMyName from CtrlTwo is successfully called, but it fails to recognize this.getMyLastName and throws

TypeError: this.getMyLastName is not a function
.

If I directly use sayMyName or getMyLastName from the CtrlOne template, everything works as expected. However, if I access them through the binding passed to componentOne, the error occurs.

What could be causing this discrepancy?

Answer №1

It is important to bind class methods that are used as callbacks to their context.

For example

class Controller {
    constructor() {
        this.doSomething = this.doSomething.bind(this);
    }
    ...
}

or

class Controller {
    doSomething = (param: string) => { ... }
    ...
}

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

- Determine if a div element is already using the Tooltipster plugin

I have been using the Tooltipster plugin from . Is there a way to check if a HTML element already has Tooltipster initialized? I ask because sometimes I need to update the text of the tooltip. To do this, I have to destroy the Tooltipster, change the tit ...

Problem with Material-UI Drawer

Is there a way to make this drawer stay fixed on the page like a sticker and remain active without moving when scrolling? I've tried using docked={false}, but it makes the whole page inactive except for the drawer. Any suggestions on how to solve this ...

Is Jade monitoring *.jade files?

Though I am not sure of the internal workings of Jade, my best guess is that it compiles each template file once and then employs a compiled and cached version for subsequent HTTP requests. One intriguing observation I have made while running my Express a ...

What is the best way to transfer an object property to an event handler function for executing DOM manipulation tasks?

I am working on a React-rendered HTML page that displays a list of objects representing websites. I have successfully stored these objects in memory and can show them in a long list on the page without any issues. Recently, I added a button for each objec ...

Tips for repairing a button using a JavaScript function in an HTML document

I am currently working on extracting titles from body text. To achieve this, I have created a button and linked my function to it. The issue I am facing is that when I click on the button, it disappears from its original position. I intend to keep it in pl ...

How to load a table file in JavaScript synchronously

I came across this particular method for accessing a local text file. However, I am facing an issue as I do not want the file to be read asynchronously. My goal is to have the function read the file and return the output as a string variable instead. The ...

What mechanism does package.json use to determine whether you are currently operating in development or production mode?

What is the process for package_json to determine when to load devDependencies as opposed to regular dependencies? How does it differentiate between local development and production environments? ...

Directive fails to trigger following modification of textarea model

There is a block of text containing newline separators and URLs: In the first row\n you can Find me at http://www.example.com and also\n at http://stackoverflow.com. The goal is to update the values in ng-repeat after clicking the copy button. ...

When filtering an array in JavaScript, ensure to display a notification if no items match the criteria

In React/Next, I have an array that is being filtered and sorted before mapping through it. If nothing is found after the filters run, I want to display a simple message in JSX format. The message should be contained within a span element. Here is the str ...

The Element is Unfamiliar - Application with Multiple Modules

I seem to be facing an issue with how my modules are structured, as I am unable to use shared components across different modules. Basically, I have a Core module and a Feature module. The Core module contains components that I want to share across multip ...

Create and export a React component with dual properties

Currently, I am utilizing MaterialUI in my project and exporting components in the following manner: import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles"; ... export default withStyles(styles)(Users); Recently, I have integrated ...

Is there a way to postpone the execution of a scheduled interval function?

Below is the setup of my function: setInterval(function () { get_fb(); }, 10000); If a user interacts with an element, such as hovering over it or clicking on it, I want to reset the timer back to 10 seconds. How can I instruct the program to achieve th ...

Improving code efficiency for checkboxes in upcoming TypeScript versions

Is it possible to create a single checkbox component and dynamically pass different values to it without repeating code? I have set up these checkboxes to help me check the maximum and minimum values of some API data. const[checkValMax, setCheckValMax]= u ...

Cypress: Importing line in commands.ts is triggering errors

After adding imports to the commands.ts file, running tests results in errors. However, in commands.ts: import 'cypress-localstorage-commands'; /* eslint-disable */ declare namespace Cypress { interface Chainable<Subject = any> { c ...

What is the best way to create a Promise that is fulfilled when an event is emitted by an event emitter in JavaScript or Node.js?

Is there a way to create a Promise in Node JS that will only resolve when a specific event is emitted by an event emitter? I am trying out the following code snippet, but I am unsure how to make the promise wait until the event occurs. function bar(resol ...

What are the steps to create an endless scrolling feature?

I'm trying to create a slider with a horizontal scrolling effect, but I've hit a roadblock. How can I make the slider scroll infinitely? In my code, you can see that after Item 6, it stops scrolling and I have to scroll backward. However, I want ...

Tips for retrieving the chosen value from an ajax.net ComboBox using javascript

Is there a way to extract the selected value from an ajax.net combobox using JavaScript for client-side validation? What would be the most effective method to achieve this? Thank you. This is how I managed to obtain the value: var combo = $get('ddl ...

Within the materia-ui table, I am facing an issue where clicking the button to expand a row results in all rows expanding. I am seeking a solution to ensure only the selected row expands

When a row is clicked, all rows in the data table expand to show inner data for each row. The issue is that clicking the expand button expands all rows rather than just the selected row. Each time I try to expand one specific row, it ends up expanding mul ...

Encountering an issue with the 'createObjectURL' function in URL, resulting in overload resolution failure when using npm file-saver

While working on my angular app, I encountered a situation where I needed to download user details uploaded as a Word document to my local machine using the angular app. Successfully, I was able to upload and save this data to my database, getting its byte ...

Having trouble retrieving the toDataURL data from a dynamically loaded image source on the canvas

Currently, I am working on a project that involves a ul containing li elements with images sourced locally from the "/images" folder in the main directory. <section class="main"> <ul id="st-stack" class="st-stack-raw"> ...