Submitting the form with an extending controller results in an undefined state

I have a primary controller and another controller where I extend the primary one to display a different layout.

Primary controller:

function CustomerInformationController(...) {
    var vm = this;
    ...

    vm.save = function() {
        if (angular.isDefined(vm.guestAccountForm)) {
            ...
        }
        ...

Primary template:

<div ng-controller="CustomerInformationController as customerInformation" class="customer-information">
    <form name="customerInformation.guestAccountForm">
    ...
    </form>
</div>

Extended controller:

function CustomerInformationControllerExtent($controller, $scope) {
    var vm = this;

    // Extend Product Controller.
    angular.extend(this, $controller('CustomerInformationController', { $scope: $scope }));

Extended template (I want to be able to redesign this template and override it):

<div ng-controller="CustomerInformationControllerExtent as customerInformation" class="customer-information">
    <form name="customerInformation.guestAccountForm">
    ...
    </form>
</div>

Everything works fine when using only the primary controller, but in the extended controller, when I try to check if the form is valid, vm.guestAccountForm is undefined.

However, when I try with this (this.guestAccountForm), it works.

Am I missing something with the extend function?

Answer №1

To streamline the process, consider injecting the vm object locally:

function CustomerInformationControllerExtent($controller, $scope) {
    var vm = this;

    // Extending Product Controller.
    angular.extend(this, $controller('CustomerInformationController', { vm  vm}));

Then, utilize the injected vm object:

function CustomerInformationController(vm) {
    ̶v̶a̶r̶ ̶v̶m̶ ̶=̶ ̶t̶h̶i̶s̶;̶
    ...

    vm.save = function() {
        if (angular.isDefined(vm.guestAccountForm)) {
            ...
        }
        ...

The this object of the xController differs from the this object of the xControllerExtent controller. This is why angular.extend is utilized, copying properties from one this object to the other.

However, it may be more efficient to avoid this approach. If you aim to share common functionalities between controllers, consider placing them in a service.

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

When you attempt to upload an MP3 file to a NodeJS Express server, the file becomes

I am facing an issue with uploading an MP3 file from my web client to a Node Express server. The uploaded file gets corrupted and I am unable to play the song using an MP3 player after writing it to disk. The problem seems to occur when uploading the file ...

The Selenium Action class is failing to perform a second mouse hover on the same web element

Actions action = new Actions(Driver); action.MoveToElement(webelement).ClickAndHold().Perform(); The code snippet above is used to perform a mouse hover on a Web Element, and it works perfectly the first time. However, when attempting to do the mouse hove ...

When `focus` is bound to a jQuery event handler, the behavior of the select element becomes erratic on

What causes the odd behavior where users need to click twice on a select-option for it to drop down/up after binding an eventhandler to the focus event using jQuery? $('input, select, textarea').focus(function() { $(this).addClass('input_ ...

Customize Bottom Navigation Bar in React Navigation based on User Roles

Is it possible to dynamically hide an item in the react-navigation bottom navigation bar based on a specific condition? For example, if this.state.show == true This is what I've attempted so far: const Main = createBottomTabNavigator( { Home: { ...

A method for dividing a string into separate characters and organizing them into an array of JSON objects

I have a collection of JSON objects with a fixed key 'type' and additional keys based on the type. Here is an example of how it looks: theArray = [ { "type": "text", "text": "= SUM(" ...

Using the attribute data-ng-repeat along with the <option> tag allows for dynamic iteration and

Hello there, I am a beginner with AngularJS and I am struggling to understand how to create my <option> list. I would like my output to resemble the example in this fiddle: http://jsfiddle.net/XdpJv/ This is what my current code looks like: <se ...

What is the best way to implement this ajax preloader?

<script type="text/javascript"> $(document).ready(function() { $('#loading') .hide() .ajaxStart(function() { $(this).show(); }) .ajaxStop(function() { $(this).hide(); }); } ...

Tips for updating button appearance when clicked using React Bootstrap

Is there a way to add custom styling to a toggle button in React? I want the button to change color when selected, but the issue is that the color reverts back to default once the click is released. Can anyone assist me with this? Below is my React Compon ...

A simple guide on accessing a local PDF file and returning it as the response for an ExpressJS application

In my ExpressJS application, I have a method for generating a PDF file and sending it to the client. However, there are cases where I need to retrieve an existing local PDF file and return it as the response. I'm unsure how to handle this scenario. ...

What is the procedure to assign a specific Id to an element within a class?

I am working with content that is dynamically loaded and I am looking to change the id of a specific element. Can anyone offer guidance on how to accomplish this task? ...

Are you planning to print the JSON information?

I've been working on mastering JavaScript and decided to create a script that displays all public Facebook statuses related to a specific keyword. However, things aren't going as planned. You can find a sample URL where the JSON data is located h ...

Javascript Library Issue: "Implicitly Declared Type 'Any' Error"

I am currently in the process of developing a JavaScript library that will interact with an API. My goal is to create a module that can be easily published on npm and utilized across various frameworks such as Angular or React. Below is the code snippet fo ...

What are the steps to develop an ElectronJS application that displays "Hello world!" in the console after a button click?

Can anyone offer a helping hand? From the depths of imagination to the realms never before conceived by humans. Check out this HTML snippet: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hell ...

Guide to incorporating d.ts file for enhancing intellisense in VS Code using a method akin to the NPM approach

In my nodejs project (in JS), I find myself relying heavily on node global variables. Despite receiving warnings against using globals, everything works well except for one thing: The lack of intellisense for globals. Every time I need to use a global fu ...

Retrieve a targeted data value from a JSON object based on an array value

Looking at the JSON array and another array provided below. JSON OBJECT { id: 1, name: 'abc', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfbebdbc9fb8b2beb6b3f1bcb0b2">[emai ...

The argument provided needs to be a function, but instead, an object instance was received, not the original argument as expected

I originally had the following code: const util = require('util'); const exec = util.promisify(require('child_process').exec); But then I tried to refactor it like this: import * as exec from 'child_process'; const execPromis ...

Ways to conceal <td>s in angularjs on specific rows during ng-repeat

In the first <tr>, I have a table with many <td> elements that I am populating using ng-repeat. <tr ng-repeat="receipt in $data"> <td data-title="voucher number"> <span>{{receipt.voucher_no}}</span> </td ...

What could be the reason behind TypeScript ignoring a variable's data type?

After declaring a typed variable to hold data fetched from a service, I encountered an issue where the returned data did not match the specified type of the variable. Surprisingly, the variable still accepted the mismatched data. My code snippet is as fol ...

Is it possible to determine the success or failure of an asynchronous function when the function itself already handles errors?

The architecture of my app is currently set up with functions that are scoped to specific modules, such as "Auth" for instance: async function authenticate(email) { let authenticated = false; try { if (email) { if (!validEmail(email) ...

Exploring the concepts of angularjs $apply and $scope within the context of object manipulation

In nearly every software application, there is a necessity to modify objects. In my scenario, I have a list of objects that can be edited on the fly with the help of Angular. However, this leads to a dilemma as exemplified by the following controller: ...