Tips for inheriting and overriding controller methods in AngularJS with Java as the base language:

I have a simple controller and I want to create a new controller that is very similar to it, but without copying too much code.

angular.module('test').controller('parentController', parentController);
parentController.$inject = ['$scope', '$location', 'someService'];

function myController($scope, $location, someService) {
    var params = getQueryString();
    var rsp = executeQuery(params);

    processResponse(rsp);

    function getQueryString() {
        return "?param=1&someparam=2";
    }

    function executeQuery(params) {
        ...
    }

    function processResponse(rsp) {
           //process rsp, convert some parts, and populate model properties, like
           $scope.model.prop1 = rsp.data.prop1;
    }
};

Now I am looking to create a new controller with 90% similarity to the parentController. The main changes needed are:

  • The getQueryString() function should return a different query
  • A single line in the response property setter for $scope needs to be changed
  • I also require additional filter functions specific to the new controller

Coming from a java background, I would solve this using inheritance and overridden methods. For example:

public cass ParentClass {
    String getQueryString() {
        return "?param=1&someparam=2";
    }
}

public class CustomClass extends ParentClass {
    @Override
    String getQueryString() {
        return "?customparam=1";
    }

    @Override
    void processResponse(rsp) {
         super.processResponse(rsp);
         //read "rsp.paramX" additionally
    }
}

But how can a similar approach be achieved with angularjs?

Answer №1

Consider the following scenario:

<div ng-controller="parentCtrl">
   ...
   <div ng-controller="childCtrl"></div>
</div> 

When the child controller is nested under the parent controller, it has access to all methods and variables of the parent controller as long as they are defined on the $scope of the parent controller (e.g. $scope.someVar).

UPDATE

If the controllers do not have a parent-child relationship, you can utilize a service to share logic. You can define an init function on the service to kickstart the process.

In your controllers, simply call myService.init() (and potentially pass parameters).

Answer №2

If you want to access parent controller properties in the child controller, you can make use of the $injector. Your child controller implementation might look like below:

function childController($injector, $scope, someService) {
    // override the method
    this.getQueryString() {
        // custom logic for new query
    }

    $injector.invoke(myController, this, {
          $scope: $scope,
          someService: someService
     });
};

For more information on this technique, refer to: https://www.example.com/angularjs-controller-inheritance/

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

Struggling with textpath SVG elements in jQuery

Currently, I am implementing SVG in my project and aiming to apply the toggleClass function using jQuery on the textpath elements upon clicking. My initial plan was: $("text#names > textpath").click(function() { $(this).toggleClass("newClass"); }) ...

I need to specify the path to the driver executable using the webdriver.chrome.driver system property, but luckily I have already set it correctly

https://i.sstatic.net/6DuU1.jpgjava.lang.IllegalStateException: I am facing an issue with setting the path to the driver executable as required by the webdriver.chrome.driver system property, even though my path is correct. if (browser.equalsIgnoreCa ...

Using JQuery to enhance the functionality of ajax-loaded content

Having difficulty implementing a more/less functionality in an ajax-loaded section of a webpage. I customized a script found at http://jsfiddle.net/gDvyR/72/, primarily by adding "on" functionality to address the ajax issue. You can view the modified ver ...

Preventing User Duplication in MERN Stack: Strategies to Avoid Multiple Registrations

A developer fairly new to the field is working on a project using the MERN stack. Within this app, there are two models: one for Users and another for Tournaments. The Tournament model contains an attribute called participants, which is an array. The dev ...

I can't seem to establish a connection with my MongoDB Atlas cluster. I encountered the MongooseError, which is as follows:

Error [MongooseError]: The uri parameter for the openUri() method needs to be a string but is currently set as "undefined". Please ensure that the first parameter for mongoose.connect() or mongoose.createConnection() is a valid string. const express = r ...

Employ a for loop to generate custom shapes within the canvas

EDIT: I will be sharing all of my code including the HTML and JS. Pardon me for the abundance of comments. I am attempting to generate rectangles in a canvas using a for loop (taking user input) and then access them in another function to perform certain ...

Can I update a label using ajax from the controller?

Hello everyone, I am facing a challenge in changing the text label coming from my Controller's JsonResult. There are two specific issues that I am encountering: 1) I am having difficulty displaying the text sent from my controller onto my view... ...

An introduction to the basics of AngularJS, AJAX, and ASP.NET MVC

I am struggling with creating a simple AngularJS example that makes an AJAX call to an ASP.NET MVC action method. I have tried various approaches but haven't been successful yet. Below is the code snippet I have been working on... The ASP.NET MVC act ...

Can you explain the distinction between Array() and [] in Javascript, and when would it be preferable to use one over the other?

Similar Question: Understanding the difference between "new Array()" and "[]" in JavaScript array declaration When working with JavaScript, you have the option to create a new array using: var arr = new Array(); or simply using: var arr2 = []; Wha ...

Add Firebase Data to Dropdown

Utilizing Vuetify to build a dropdown has been an interesting challenge for me. While I can successfully select a value and store it in the firebase database, I'm facing difficulties when it comes to repopulating the dropdown after page refresh. Belo ...

What are the steps to store a firebase storage downloadURL in a firestore collection?

I'm facing an issue with saving my firebase storage image into a firestore collection variable. Initially, it was working correctly but suddenly stopped functioning, and now the image variable is returning null. Note: I am using the asia-south1 serve ...

Exploring the power of NodeJS with nested functions for conducting in-depth search

Hey there, friends! I'm currently working on a small web application using NodeJS. One of the key features in my app is a search functionality that spans across different pages. However, I have some doubts about the nested functions related to this s ...

Tips on locating a particular user on the Smack messaging platform

I've been grappling with this issue for a few hours now. Currently, I am in the process of learning about the smack API. The problem arises when searching for a buddy (user), as it returns all matched options instead of just the exact match. Take, for ...

Embedding complex JSON information into an HTML dropdown menu

Here is a JSON string that I am working with: { "electronics": { "cameras": [ "sony", "nikon", "canon" ], "TV": "none", "laptop": [ "hp", "apple", "sony" ] }, "home": { "furniture": [ ...

How to read a text file in JavaScript line by line

Coding Challenge: <script src="../scripts/jquery-3.1.0.min.js"></script> <script> $(document).ready(function(){ $('#test').click(function(){ var txtFile = '../data/mail.txt'; var file ...

Nuxt: Encountered an unexpected < symbol

https://i.sstatic.net/MbM9f.png I've been working on a nuxt project where I'm currently in the process of creating a map component using Google Maps with the help of the plugin https://www.npmjs.com/package/vue2-google-maps. After installing the ...

The format of the date cannot be modified when using DesktopDatePicker as a React Component

I've been attempting to modify the appearance of the component, but the UI keeps showing the date in month-year format. <DesktopDatePicker inputVariant="outlined" label="Pick-up date" id="date ...

Encountering an issue with the v-carousel component from Vuetify: receiving a 'Cannot read property 't' of undefined' error message

Currently, I am trying to create an image carousel using Laravel along with Vue/Vuetify. The issue lies in the fact that the Vuetify v-carousel and v-carousel-item components are not rendering properly due to the error mentioned in the title. I have alrea ...

Adjust the size of a Highcharts chart before printing

I'm facing an issue with a chart that doesn't have a specified height or width. My goal is to print the graph in a taller and larger size when I click on the print button. I attempted to use setSize() function, but since there are no original di ...

Displaying random divs and subsequently animating them downwards using JavaScript

I am in the process of creating a random appearing div that then falls down. Here is the code I have so far: $(document).ready(function(){ $('#test').animate({top: 80 + '%'},900); }); <div id="test" style="background:#98bf21;heigh ...