Expanding a controller in AngularJS

Currently, I am using Angular to develop a large application and I have some common methods for controllers. As of now, this is how I am implementing it. However, is there a better way to approach this?

app.controller('baseController', function($scope, $controller, appFactory) {
    var $scope.foo = function() {
        // Perform certain actions
    }
});


app.controller('childController', function($scope, $controller, appFactory) {

    // Here I am extending or something similar to the base controller

    $controller('baseController', {$scope: $scope});

    var $scope.bar = function() {
        // Perform multiple actions and then call foo
        $scope.foo();
    }
}):

I am following this approach because these methods require access to the $scope of my controller.

Answer №1

Contrary to some opinions, I believe that implementing inheritance for controllers can be beneficial. In many scenarios, controller inheritance can help maintain DRY code even when using shared services, factories, or providers. For example, instead of duplicating

$scope.foo = function() { MyFactory.calculateFoo(); }
across multiple controllers, you could consolidate it in a base controller. This approach not only streamlines the controller but also promotes code reusability.

Misko himself referenced an AngularJS google group discussion showcasing a method for implementing controller inheritance. Personally, I adopt a similar approach where I call a base controller from within my child controller:

$injector.invoke(MyBaseController, this, { $scope: $scope, alertService: alertService });

One practical application of controller inheritance in my projects is on CRUD pages. I have a parent controller that handles generic create/update $scope functions and interacts with a repository service for server calls. Rather than repeating this setup for every CRUD page, I leverage controller inheritance to streamline the implementation.

Answer №2

Expanding on the point made by KayakDave, Angular controllers are typically designed to be lightweight. If you catch yourself considering "Inheritance" within a controller, it could indicate that you're approaching it the wrong way. The recommended approach is to move common functionality shared across controllers into a Service/Factory/Provider. This restructuring can lead to improved code organization and overall efficiency.

app.Factory('MyFactory', function() {
    return {
        calculateFoo: function() { 
          // logic for calculating Foo
        }
    };

});

app.controller('FirstCtrl', function($scope, $controller, MyFactory) {
    var $scope.foo = function() {
        MyFactory.calculateFoo();
    }
});


app.controller('SecondCtrl', function($scope, $controller, MyFactory) {

    var $scope.bar = function() {
        MyFactory.calculateFoo();
    }
}):

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

Why am I not receiving recommendations for the data types of a function parameter when there are multiple variations available?

I'm currently navigating a JavaScript codebase that utilizes Sequelize models with documented types specified in TypeScript declaration files (.d.ts). Within my code, I am utilizing model.update() to modify certain properties on the object: To replic ...

Tips for showing the previous value associated with a specified value in an array using JavaScript

Is it possible to retrieve the previous value of a given input from an array? If so, how can we achieve this? var theArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 14, 15]; const findValue = (arr, input) => { // To do } findValue(theArray, 15) If we provide the ...

What is the best method for embedding JSON data into a script tag within a Zope Chameleon template?

Creating a pyramid/python application where the view callable passes in an array variable called data, structured as [[[x1,y1,z1,],...],[[v1,v2,v3],...]] In the view callable: import json jsdata = json.dumps(data) I aim to place this data within a java ...

What is the best way to test an oclif CLI tool that interacts with a Rest API

How can I efficiently test the TypeScript code I've written for an Oclif CLI that interacts with a Node.js and Express.js REST API? I'm currently using Mocha/Chai for testing, but I'm struggling with testing the specific command code from my ...

The feature to dynamically insert additional fields includes two dropdown menus (one for selecting category and one for product) and an input box for entering a price

I am looking to dynamically populate two dropdown menus and an input box based on data fetched from a database. The first dropdown should populate categories, the second dropdown should display products based on the category selected, and the input box sho ...

What is the best way to notify a JavaScript client from Laravel when a save operation is performed on the database?

Is there a way to automatically refresh the JavaScript DOM when the database is updated, without having to reload the page? Initially, I considered sending an Ajax post request with a 3-second delay, but I've realized that it's not a good idea. ...

Issue in React: Unable to choose options from a dropdown menu once a value attribute has been assigned to the component's state

One issue I encountered with my React component that renders a dropdown menu is that although it successfully re-renders the value when new props are received, it disables the option to select a different value. This behavior occurs because I have set th ...

Solidity: Difficulty retrieving values from my smart contract in React

In my solidity file, I have a method called "cote" app.sol : function cote() public view returns (uint256){ return data; } App.js : class App extends Component { constructor(){ super(); this.state={ web3 ...

eslint alert: The aria-current attribute must have a value that is a single token from the following list: page, step, location, date, time, true

<div role="button" tabIndex="0" className="nav-link pad-0-r" aria-current={'${selectedTab === item ? 'page' : 'false'}'} onClick={()=> onClick(item)} onKeyDown= ...

Activate the script upon the left-click of the arrow icon

Looking for help with this basic javascript code snippet. $('#about_us').on('click',function() { $('#slider').toggleClass('open'); }); I'm trying to find a way to activate this function by pressing the lef ...

Having trouble with the search function in my array, as it is consistently returning false instead of the expected result

Aim: I am working on creating a basic search bar that allows users to input a zip code and matches it with zip codes stored in an array. The objective is to develop a function that can determine whether the entered zip code exists in the array or not, and ...

Unable to save the newly generated data into MongoDB

I'm currently working on a small project where users can generate random hex colors and save them to a database. However, I seem to be encountering an issue as the data is not being saved to the database. My index.js file serves as the main file for d ...

Header Overflow Error Encountered in Node.js GET Request

While attempting to programmatically submit a form through Google forms using a GET request, I encountered the error message Parse Error: Header overflow. The debug code output is as follows: REQUEST { uri: 'https://docs.google.com/forms/d/e/9dSLQ ...

Extract the Top X elements from a multidimensional array

Consider an Array that consists of nested arrays: [ ["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a9a8abe091b6bcb0b8bdffb2bebc">[email protected]</a>", 1, 9, 338], ["2000-01-01", "<a href="/ ...

Wait until the user submits the form before activating Angular validations, and do not display any validation messages if the user deletes text from a text box

I am looking to implement angular validations that are only triggered after the user clicks on submit. I want the validations to remain hidden if the user removes text from a textbox after submitting it. Here is what I need: - Validations should not be dis ...

Is it recommended to exclude the NGXS NgxsLoggerPluginModule for production deployments?

When developing, it's common to use the following imports: import { NgxsReduxDevtoolsPluginModule } from '@ngxs/devtools-plugin'; import { NgxsLoggerPluginModule } from '@ngxs/logger-plugin'; Is it recommended to remove these imp ...

Using Puppeteer to cycle through a CSV file and take a screenshot for each individual row?

I am looking to automate screenshotting URLs from a CSV file using puppeteer, but the current code execution is slow as each request waits for the previous one to finish. const csv = require('csv-parser'); const fs = require('fs'); con ...

Diagnosing Issues with Yii2's $(document).ready Function

AppAsset: public $js = [ 'plugins/jquery/jquery.min.js', 'plugins/jquery/jquery-migrate.min.js', 'app.js', ]; When I write this in a view file: $script = <<< JS jQuery(document).ready(function( ...

unemployed with XMLHttpRequest not functioning

I have exhausted all recommended solutions for similar issues, yet this simple code refuses to work. My goal is to retrieve a message from the PHP code in the same file using XMLHttpRequest. <!DOCTYPE html> <head></head> <body> < ...

What is the best way to eliminate excess space on the right side in Bootstrap 4 while in mobile view?

I'm struggling to understand why this layout is not responsive on mobile devices, triggering a bottom scroll bar at around 616px. I'm looking for a solution to hide the scroll bar at least until 414px for iPhones and other smartphones. I've ...