Encountering the error message "Function.prototype.bind.apply(...) cannot be invoked as a constructor

I'm attempting to implement Controller Inheritance in AngularJS (1.6.9), but encountering an error in the console: Function.prototype.bind.apply(...) is not a constructor. Here's the snippet from the HTML file:

<!-- Controller Inheritance -->

<!DOCTYPE html>
<html lang="en" ng-app="app7">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Tutorial 7</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<div ng-controller="mainCtrl as parent">
  <p>Name: {{parent.name}}</p>
  <p>Sound: {{parent.sound}}</p>
  <button ng-click="parent.animalClick()">Animal Data</button>
</div>
<br><br>
<div ng-controller="dogCtrl as dog">
  <p>Name: {{dog.child.name}}</p>
  <p>Sound: {{dog.child.sound}}</p>
  <button ng-click="dog.child.animalClick()">Dog Data</button>
  <button ng-click="dog.child.dogData()">Get More Data</button>
</div>
  <script src="js/exam7.js"></script>
</body>
</html>

And here's the corresponding code from the JS file:

//Controller Inheritance Demonstration

let app7 = angular.module('app7',[]);

//Parent Controller

app7.controller('mainCtrl',()=>{
  this.name="Animal";
  this.sound="Silent";

  this.animalClick= ()=>{
    alert(this.name+' says '+this.sound);
  };
});

//Child Controller

app7.controller('dogCtrl',($controller)=>{
  let childCtrl = this;
  childCtrl.child=$controller('mainCtrl',{});
  childCtrl.child.name="Dog";
  childCtrl.child.bark="Woof"; //child`s own variable

  childCtrl.child.dogData = ()=>{
    alert(this.name+' says '+this.sound+' and '+this.bark);
  };
});

I'm striving to inherit mainCtrl within childCtrl, but facing difficulties. The output is not matching expectations. Any insights into why this particular error is occurring?

Answer №1

Not all instances in AngularJS support the arrow notation.

When AngularJS attempts to call a function using the new your_function(){...} method, treating it as a class, it cannot do so with the arrow notation new ()=>{...}.

To resolve this issue, simply update

app7.controller('mainCtrl',()=>{

to

app7.controller('mainCtrl',function(){

(and make similar changes elsewhere)


There was also an error in how you were printing child values. You must access the .child. sub-property before attempting to print any data.

Here is a corrected version of your code:

let app7 = angular.module('app7', []);

//Parent Controller

app7.controller('mainCtrl', function() {
  this.name = "Animal";
  this.sound = "Silent";

  this.animalClick = () => {
    alert(this.name + ' says ' + this.sound);
  };
});

//Child Controller

app7.controller('dogCtrl', function($controller) {
  let childCtrl = this;
  childCtrl.child = $controller('mainCtrl', {});
  childCtrl.child.name = "Dog";
  childCtrl.child.bark = "Woof"; //child`s own variable

  childCtrl.child.dogData = () => {
    alert(this.child.name + ' says ' + this.child.sound + ' and ' + this.child.bark);
  };
});
<!DOCTYPE html>
<html lang="en" ng-app="app7">

<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Tutorial 7</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>

<body>
  <div ng-controller="mainCtrl as parent">
    <p>Name: {{parent.name}}</p>
    <p>Sound: {{parent.sound}}</p>
    <button ng-click="parent.animalClick()">Animal Data</button>
  </div>
  <br><br>
  <div ng-controller="dogCtrl as dog">
    <p>Name: {{dog.child.name}}</p>
    <p>Sound: {{dog.child.sound}}</p>
    <button ng-click="dog.child.animalClick()">Dog Data</button>
    <button ng-click="dog.child.dogData()">Get More Data</button>
  </div>

</body>

</html>

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

Are the results displayed in a vertical array format?

Being new to this world, I would greatly appreciate any assistance! I am working with Bootstrap checkboxes and trying to print them using jQuery's window.print function. However, the issue I am facing is that the array I create from the checkboxes d ...

Update the directive automatically whenever a change occurs in the root scope property

I am facing an issue with a directive that generates a random number. My goal is to reload or refresh this directive when a checkbox is toggled. Below is the code I have been using, but unfortunately, it's not working as expected. var app = angular. ...

The privateroute is throwing an error because it cannot access the property state since

I stumbled upon a tutorial online detailing how to construct a customized private route, but alas, I am encountering an error. Upon execution, I am faced with the dreaded message: "Cannot read property 'state' of undefined" on line 12. As someon ...

Using React to showcase a base64 image representation

I'm struggling to show an image that has been sent from my Node/Express server to my React application. I've tried looking at solutions on other platforms, but so far nothing has worked for me. Let me outline the steps I have taken: The image is ...

Angular bootstrap datepickers will pop up when the user hits the Enter key on a different input field

I am working on a search form that includes 2 datepickers, one for 'from' date and the other for 'to' date. Additionally, there are input fields for various search criteria and a submit button. The issue I am facing is that when a user ...

Localized Error: The property 'clientWidth' cannot be retrieved as the object is null or undefined

The issue with the error message seems to only occur on Internet Explorer, and unfortunately there doesn't seem to be a clear solution at the moment. Even after setting http-equiv="X-UA-Compatible" to IE8, the problem persists and I cannot seem to re ...

Transforming various date formats into the en-US format of mm/dd/yyyy hh:mm:ss can be accomplished through JavaScript

When encountering a date format in en-GB or European style (mm.dd.yyyy), it should be converted to the en-US format (mm/dd/yyyy). If the date is not already in en-US format, then it needs to be converted accordingly. ...

What are some creative ways to customize and animate the cursor or caret within an input field?

Just to clarify, I am working with React and Material-UI. I have a task at hand where I need to modify the appearance of the caret within an input element by adding an animation to it. I have managed to change its color using caret-color and set a default ...

What happens with the styling in this project when the CSS file is blank?

As a first-year CS student in university, I have been diving into the world of React.js. Currently, I am exploring a resume project and noticed that both app.js and index.js files are empty. I am curious to know how the styling is achieved in this project. ...

What is the best way to transfer all li elements with a certain CSS style to a different ul?

I have a task to relocate all the <li style="display:none;"> elements that are currently nested under the <ul id="bob"> into another <ul id="cat">. During this relocation process, it is important that all the classes, ids, and CSS style ...

Transforming JSON information for Google chart data table

I am currently working on converting JSON data into a suitable format for a Google Chart visualization: var jsonData = {"Battery Voltage, (A)": {"2017-11-11T00:00:00.000Z":12.3, "2017-11-11T00:01:00.000Z":12.35, ...

Leveraging the Power of JavaScript within Angular 12

Currently, I am in the process of learning how to utilize Angular 12 and am attempting to create a sidenav. While I am aware that I can use angular material for this task, I would prefer not to incorporate the associated CSS. My goal is to integrate this ...

Unable to change the variable for the quiz

Currently, I am in the process of developing a quiz app and I am facing an issue with my correct variable not updating. Whenever I trigger the function correctTest() by clicking on the radio button that corresponds to the correct answer, it does get execut ...

Steps for modifying an element in an array using Javascript

Currently, I am a beginner in the realm of JavaScript and I am trying to build a todo-style application. So far, I have successfully managed to create, display, and delete items from an array. However, I am facing challenges when it comes to editing these ...

React- The Autocomplete/Textfield component is not displaying properly because it has exceeded the maximum update depth limit

My autocomplete field is not displaying on the page even though I wrapped it with react-hook-form for form control. When I check the console, I see this error: index.js:1 Warning: Maximum update depth exceeded. This can happen when a component calls setSt ...

What is the process for uploading a text file into JavaScript?

I'm currently facing an issue with importing a text file from my local computer into JavaScript in order to populate HTML dropdowns based on the content of the file. Despite spending considerable time searching for solutions on stack overflow, I haven ...

What is the process for including item prices in Angularjs?

I have a question regarding adding work item costs and encountering issues with displaying the original values. Here's an example: item[1].cost = 2, item[2].cost = 2 .. When I add the cost of the 3rd item (item[3].cost = 8), the total shows as 228. ...

What steps can I take to resolve my password validation rule when confirming during sign-up?

Utilizing react-hook-form in combination with Material-UI for my sign-up form has been a challenge. I am currently working on implementing a second password field to confirm and validate that the user accurately entered their password in the initial field, ...

Utilizing ReactJS to dynamically display various content based on onclick event

Is it possible to dynamically display different content based on button clicks? I want to create a schedule where clicking on specific days like Monday will reveal exercises and timings only for that day. The same goes for Thursday and other days. You ca ...

Retrieve the date from the event

Incorporating fullcalendar v2.0.2, I am currently developing a copy/paste system for events. By right-clicking, I am able to copy the event with the help of a small menu. Upon right-clicking on the calendar during a week view, I am tasked with calculating ...