"Create a new controller with Angular using the constructor method

Looking to consolidate common functionality in my controllers, I want to utilize inheritance in a parent controller instead of creating a service. Most examples utilizing the $injector.invoke function require the parent's constructor function to be accessible. For example: http://plnkr.co/edit/kva82QyytKQfOafGiVxL?p=preview.

Since each of my controllers is stored in separate files, I aim to implement the following:

The parent controller resides within its own module:

angular.module('app.parent').controller('ParentCtrl', function() {
    this.someMethodProvidedbyParent = ....
});

The child controller extends ParentCtrl using $injector.invoke. How do we access ParentCtrl?

angular.module('app.parent.child').controller('ChildCtrl', function($injector) {

    // We need to fetch ParentCtrl from the angular module 'app.parent'
    $injector.invoke(ParentCtrl, this, {});
});

I could potentially place ParentCtrl in a global object, but I prefer leveraging the angular module system.

Answer №1

Successfully achieved the task by instantiating the parent controller and utilizing angular.extend in this manner:

app.controller('ChildCtrl', function($controller) {
  angular.extend(this, $controller('ParentCtrl'));

  // Customizing methods here (after extending `this`)
});

Attributes from the parent are replicated to this.

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

What is the best way to incorporate my Axio post into the submission process of my upload form while utilizing a custom hook for validating the form data?

Currently facing a challenge with allowing users to submit an image file (.jpeg, .png) along with a title for that image (text) through my backend API. The issue arises from using a custom hook called useForm in the upload component to fetch validation fun ...

The Fusion of JavaScript Frameworks

Is it considered poor practice for a seasoned developer to build a web application using multiple JS frameworks? For instance, when incorporating AngularJS into a project, and certain tasks could be more efficiently achieved with JQuery, should one opt fo ...

PHP and JS with Jquery often face challenges when trying to work together due to their conflicting array structures

This is a perplexing issue that has me stumped. I retrieved an array of workers from a MySQL database using json_encode and then copied it to two other arrays for future operations. var workers = <?php echo json_encode($tablica_pracownikow); ?>; va ...

Is there a way to verify if a user taps outside a component in react-native?

I have implemented a custom select feature, but I am facing an issue with closing it when clicking outside the select or options. The "button" is essentially a TouchableOpacity, and upon clicking on it, the list of options appears. Currently, I can only cl ...

Resource file for locating the mappings

As a beginner in sourcemapping, I have been tasked with saving the sourcemap in an external file. However, up to this point, I have only been able to concatenate the sourcemap to the minified .js file. What changes should I make to my approach? Am I miss ...

Conceal the navigation bar when scrolling to the top of the

Hey there! I'm looking for a way to hide my navigation bar when not scrolling, and then display it again once I start scrolling. Currently, I have two menus on this website: one with a white background and the other with a blue background. You can fi ...

Choose the Nth option in the dropdown list using programming

Currently, I have a script that dynamically populates a select box with unknown values and quantities of items. I am looking to create another script that mimics the action of selecting the Nth item in that box. Despite my research, I have been unable to ...

Comparing prevProps and this.props in React Native Redux: What is the most effective method?

Does anyone know how to efficiently handle triggering a function in my React Native app only when a specific prop has changed? This is the current implementation I have: componentDidUpdate(prevProps) { if (prevProps.a !== this.props.a) { <trigger ...

Is it possible for parameters to still be filled even when they start off empty

Currently, I am enrolled in a javascript course and struggling to comprehend how the parameter in my example below is populated with the "correct stuff" without actually calling the function with a corresponding element? success: function(result) { ...

Embracing the AngularJS approach to displaying values on a user interface

Looking for guidance on a beginner issue with AngularJS: I have an application where the API returns values from a list of possible types. I want to map these values to specific icons for each type, and I will likely need to reuse this mapping logic frequ ...

Ways to verify if two items within a collection of objects share a common value in MongoDB

I have a collection of data called users stored in mongoDB that has the following structure: _id: ObjectId, sports: [ { name: 'cricket', history: [ { from: 10, to: 30 }, { from: 30, to: ...

Personalize the iOS smartbanner

We have a plan to incorporate smart banners into our app. Is there a way to personalize the smart banner so that the close button is hidden and cannot be closed by the user? I attempted to use a jQuery plugin (https://github.com/jasny/jquery.smartbanner) ...

"Exploring the Art of Showcasing Duplicate Image Count from User Input in an

I need to showcase multiple duplicates of 2 different images on a webpage. Users are asked for the duplication speed, which I have already implemented, and also how many copies of each image they want. function show_image() { var img = document.create ...

ways to manipulate href using JavaScript

Apologies for any grammatical errors in my English. With the use of jQuery, I am trying to achieve the functionality where pressing the arrow keys on the keyboard will redirect to a URL with the #g tag. Specifically, when the down arrow key is pressed, h ...

Encountering an error in a React application with Redux: "Unable to access the 'state' property of undefined"

I'm currently working on a react redux application where I want to add a message to the message array in the reducer's initial state when the add message button is pressed. However, I encountered an error "TypeError: newstate1.user.id.find is not ...

AngularJS docker image that can be reused

Our team has developed an AngularJS application and crafted a dockerfile for it to ensure reusability across different systems. While the dockerfile may not adhere to best practices and could be considered unconventional due to combining build and hosting ...

Exploring arrays through nested for loops to draw comparisons

Issue: I have two arrays, one representing Alice's scores and the other Bob's scores. The task is to compare the scores at each index for both players and award a point to the player with the higher score (no points if the scores are equal). INP ...

What is the most foolproof method for detecting when a checkbox has been marked as checked, regardless of the circumstances?

Is there a way to detect changes in the checked value of a checkbox when it is changed by a script that I do not control? I have tried using `addEventListener()` and jQuery's `on()` method, but they do not work in all cases. <input type="checkbox" ...

Error: The function 'drawImage' on 'CanvasRenderingContext2D' could not be executed due to the HTMLImageElement being in a 'corrupted' state

import { Bodies, Composite, Engine, Mouse, MouseConstraint, Render, Runner } from 'matter-js'; import React, { useEffect } from 'react'; import * as S from './styles'; import flutter from '../../../../public/Icon/flutterL ...

Converting Custom Data Arrays to JSON using JavaScript

My goal was to create a utility function that can convert custom data (the type of data Sencha Touch stores use) into JSON format. I've made progress, but the function fails when dealing with complex data from the Twitter API, although it works fine w ...