Angular: Utilizing the extend method in the child controller's scope

I am facing a challenge regarding the extension of methods in an angular child controller which is causing me some frustration. My main objective is to inherit all the public /$scope/ variables and methods from the parent controller into the child controller, while also adding more functionality to specific functions. This is what I have so far:

var app = angular.module("conrollersInheritance", []);

app.controller("parentController", [
    "$scope",
    function ($scope) {
        /* PRIVATE */
        var privateVar1 = "private variable 1";
        var privateVar2 = "private variable 2";

        // ...Other private declarations...

        /* PUBLIC */
        $scope.publicVar1 = "public variable 1";
        $scope.publicVar2 = "public variable 2";

        $scope.showVars = function () {
            console.log("PRIVATE: ", privateVar1, privateVar2);
            console.log("PUBLIC: ", $scope.publicVar1, $scope.publicVar2);
        };

        // ...Other public functions...
    }
]);

app.controller("childController", [
    "$scope", "$controller",
    function ($scope, $controller) {
        $controller("parentController", { $scope: $scope });

        $scope.showVars = function () {
            alert("child scope");
            // ???Here I want to execute the inherited method from the `parentController`
        };
    }
]);

The issue I'm encountering is that the childController is inheriting all the $scope data from the parentController, but I'm unable to extend the functionality inherited as it keeps getting overridden. I've tried various approaches based on Angular documentation which states that the $controller service should return the instance / https://docs.angularjs.org/api/ng/service/$controller /, but in my case it always returns an empty constructor object. When I try:

var parentController = $controller( "parentController", { $scope: $scope } );

I always get an empty object for the parentConroller variable and cannot use anything inherited from it. I attempted to declare a viewmodel inside the childController using:

var vm = this;
$controller( "parentController", { vm: $scope } );
angular.extend( $scope, vm );

However, this approach results in an error when trying to extend the scope. I also tried:

$scope.showVars = function() {
    alert( "child scope" );
    vm.showVars();
};

But still faced difficulties in implementing this. I have read many tutorials suggesting that the above methods should work, but they do not seem to be effective in my situation. Any suggestions or ideas would be greatly appreciated. Thank you!

Answer №1

With prototypical inheritance in play, your child controller automatically inherits all properties/methods from the parent's $scope when nested.

You have two options for nesting controllers: either using ui-router and defining a child state

.state('route', {
    controller: 'ParentController',
    // additional route configuration
})

.state('route.child', {
    controller: 'ChildController',
    // additional route configuration
})

or by directly nesting them within the template

<div ng-controller="ParentController">
    <div ng-controller="ChildController">
        <!-- continue with the rest of your template -->
    </div>
</div>

Afterward, you can easily extend the method from your ParentController like so:

$scope.showVars = () => {
    $scope.$parent.showVars();
    // add your custom logic here
};

This results in creating a new showVars method on the $scope of your ChildController, which will be utilized by default in your template instead of the inherited one from the ParentController.

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

unable to render the JavaScript code

Utilizing JavaScript post an ajax request to showcase the data in a div using new JS content. The example code is provided below: //ajax call from a.jsp var goUrl = "/testMethod/getTestMethod; var httpRequest=null; var refreshCont ...

Using Angular 2 for two-way binding with input masking

Encountering an issue with ng2 and inputmask. Here is the code snippet that's causing trouble: <div class="form-group col-sm-7"> <label class="control-label" for="sender-phone">Phone *</label> <input type="text" [(ngModel) ...

Switching jQuery on various sections of a webpage

In my attempt to replicate the functionality of Facebook's Like button, I have encountered a challenge regarding where exactly to click in order to change the button state. When the button is not liked yet, users should be able to click anywhere on t ...

The requested `GLIBC_2.28' version required by node cannot be located, leading to an inability to amplify the version

While there were numerous questions about this topic, I am specifically seeking solutions for amplify. Below are the logs from my amplify build: 2024-01-14T16:14:17.626Z [INFO]: # Cloning repository: <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

How can I programmatically trigger a change event for a dropdown in Vue.js?

I am looking to trigger a dropdown change event within a Vue.js method. <select id="idDropdown" v-model="Result.Value" v-on:change.prevent="changeSelection($event, 'somevalue')"> How can I call the above `cha ...

Unable to establish a connection with the Mysql database using Node JS

My Class is responsible for handling a mysql connection, and every time I access the path /cargos, it should retrieve data and then close the connection. However, every time I try to Query, I encounter this error message: TypeError: conexao.query is not a ...

The seamless integration of AngularJS and the chosen library is proving to be

When I use a chosen select to load data from a JSON file in an AngularJS application, the data loads successfully with a standard HTML select. However, if I switch to using the chosen select, the data does not load. I understand that the data is fetched af ...

What is the best way to set up callbacks for an AngularStrap or Angular UI Bootstrap Popover, to run when the popover is opened and closed?

I am currently exploring the functionalities of the Angular UI Bootstrap popover and I have a particular need to define callback functions for both when it is opened and closed. The purpose behind this requirement is that I intend to utilize the popover fo ...

An error was encountered: $controllerProvider provider is not recognized within the productsApp

Here is the link to my code: http://plnkr.co/edit/8muxhJmvFiIqRJgzuT0O?p=preview I encountered an error: Uncaught Error: Unknown provider: $controllerProvider from productsApp Additionally, I am unable to view the JSON file in the console. index.html ...

Can a variable be declared within the path references of the Firebase database?

In an effort to update my app's database references, I am working on implementing specific Firebase rules that involve adding buildings and depts nodes inside the user node. This decision was prompted by a discussion on best practices for writing Fire ...

How to use Javascript 'if statement' to check for a numerical value in a form field?

I am currently using some JavaScript within a Mongoose Schema to automatically increment a value if no number is manually entered in the form field. // before validation starts, the number of Items is counted..afterwards, the position is set ItemSche ...

Could you show me how the easyrtcid is generated in the demonstration of audio-only chat? I would appreciate a step-by

Currently, I am utilizing the easyrtc webpage to test out the audio only chat demo and everything seems to be running smoothly. However, when connecting, the easyrtcid variable is automatically assigned a random string. I was wondering if there is a way t ...

Utilize the composition API in Vue.js 3 to call a function and pass in a parameter

I'm having trouble calling a function from another component. When I click on a button in my parent component, formTelemarketing(), it should send data to my other component nAsignedCalls() and call the function getCalls(param) in that component. Thi ...

Updating content in AngularJS based on the sidebar can be achieved by following these steps:

Yesterday, I posed a question about how to implement multiple views with Angular in order to have a header and sidebar. After receiving some helpful insights, I was able to make progress on creating a header and sidebar for my AngularJS App. You can view ...

Checking CORS permissions with a pre-flight OPTIONS request

During development, I implement a middleware called cors using the following syntax: app.use(cors({origin: 'http://localhost:8100'})); However, I have noticed that for every route request, two requests are being made as shown in the image below ...

The fixed blocks are covering the Blueimp gallery within the relative container

Check out this DEMO I created to showcase something interesting. In this demo, you will find a basic example of setting up a blueimp gallery, a navigation bar, and a button. <div class="nav">nav</div> <div class="wrapper"> <div id ...

The Jquery watermark extension in IE9 is capable of transmitting the watermark as the primary value of the form

I have integrated a plugin into my project. The plugin can be downloaded from this link. However, I am facing an issue where the watermark value is being submitted as the textbox's value in Internet Explorer 9. How can I resolve this problem? Intere ...

Using a React component to trigger an action when the Enter key

I have a react component that needs to respond to the "Enter" key press event. class MyComponent extends Component { componentDidMount() { console.log('componentDidMount'); document.removeEventListener('keypress', t ...

An issue has occurred: The necessary parameter (Slug) was not included as a string in the getStaticPaths function for the /post/[Slug] route

Hello, I've recently embarked on a tutorial journey to create the ultimate Modern Blog App using React, GraphQL, NextJS, and Tailwind CSS. However, I encountered an error that's giving me some trouble specifically when trying to access a post. He ...

Attempting to execute Javascript code from within Java programming environment

One of my JavaScript code snippets utilizes another external JavaScript source: <body> <script src="node_modules/node-vibrant/dist/vibrant.js"></script> <script type="text/javascript"> function test(src) { Vibrant.fr ...