Increasing the number of controller methods in Angular

Within AngularJs, I have multiple controllers that share similar functions:

angular.module('myApp').controller(...){

    function lockForm(id){
        ...
    }

    function releaseForm(id){
        ...
    }

    function dbError(e){
        ...
    }

    // and other repetitive tasks in each controller
}

The examples I've come across usually involve extending (mixing) properties from $scope and @this. Is there a way to extend the entire controller itself?

Thanks to Shushanth Pallegar, I managed to solve my problem. It might not be exactly what I was looking for, but it's definitely an improvement.

// base ctrl
angular.module('myApp').controller('baseViewCtrl', function ($scope, viewData) {

        this.lockForm = function() {
            viewData.isLoading = true;
        };

        // ... and more

});


// child ctrl
angular.module('myApp').controller('childCtrl', function ($scope) {
        var viewData = {
            // some data
        };

        // inherit from basecontroller
        angular.extend(this, $controller('baseViewCtrl', {$scope: $scope, viewData: viewData}));

        // link $scope
        $scope.viewData = viewData;
        $scope.onSelectUnit = onSelectUnit;

        // child controller methods
        function onSelectUnit(){
            this.lockForm();
            ...
        }
});

It may look messy because I used @this sparingly throughout the code.

I'm considering using 'base' instead of @this to clarify that these are injected methods:

// child ctrl
angular.module('myApp').controller('childCtrl', function ($scope) {
        var viewData = {
            // some data
        };

        // inherit from basecontroller
        var base = $controller('baseViewCtrl', {$scope: $scope, viewData: viewData});

    // link $scope
    $scope.viewData = viewData;
    $scope.onSelectUnit = onSelectUnit;

    // child controller methods
    function onSelectUnit(){
        base.lockForm();
        ...
    }

Answer №1

Utilize the $controller service to extend the functionality of a controller by following these steps:

Parent Controller

  angular.module('myApp').controller('parentController',function(){

     $scope.lockForm = function(id){
        ...
    }
  });

Child Controller

angular.module('app').controller('childController',function($controller){

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

     console.log(parentController.lockForm);

  });

For more information, refer to the $controller documentation.

To extend 'this' in the child controller, use the method below:

angular.module('app').controller('childController',function($controller){

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

     console.log(this.lockForm);

  });

If you are using functions that are attached to scopes, make sure to return those functions as shown below.

 angular.module('myApp').controller('parentController',function(){

         var _lockForm = function(id){
            ...
        }

       return{
          lockForm: _lockForm
       }

      });

Then, in your extended controller, you can utilize the function like this:

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

    extendeController.lockForm('123');

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

Error message encountered when submitting a form after receiving an AJAX response: VerifyCsrfToken Exception

I'm encountering an issue with my AJAX functionality that involves rendering a form with multiple input fields and a submit button. Here is the AJAX call: <script type="text/javascript"> $('#call_filter').click(function() { $.aja ...

Loop through an array of values in AngularJS

Here is an example of an array: [ {type:'x', value:'123'}, {type:'y', value:'456'}, {type:'z', value:'789'}, {type:'w', value:'012'}, {type:'q&apo ...

The imported symbol from the typescript library cannot be found

Currently, I am in the process of developing a React/Redux application using Typescript. My goal is to streamline development by creating libraries for each unique "domain" or "feature" that will contain domain-specific details and provide an API to the ma ...

Utilize a separate function within the ngOnInit() lifecycle hook

Currently, I am developing a mapping application using OpenLayers (4.6.5) within Angular (6). In order to execute requests and retrieve GeoJSON files, I am utilizing a French API made available by the French government. Previously, I successfully implemen ...

"We are experiencing issues with the app.get function and it is

Although my backend is successfully serving other files, I have encountered an issue with loading new files that are located in a folder named js within the directory. These specific files are not being loaded, and despite spending an hour trying to troubl ...

Unable to load JavaScript files on the client side

Currently, I am in the process of learning how to develop an NPM package. Initially, I assumed it would be a simple task: create JS files with object literals, export modules, and then have users require the file and utilize the object like objectname.meth ...

Unable to open fancybox from a skel-layer menu

Seeking assistance with integrating a Fancybox inline content call from a Skel-layer menu (using the theme found at ) <nav id="nav"> <ul> <li><a href="#about1" class="fancybox fancybox.inline button small fit" >about< ...

Encountering an 'Unexpected token x in JSON at position 1' error while attempting to parse a JSON string embedded within HTML

I've been attempting to convert a hardcoded JSON string into a usable format, but I am struggling to make it work properly. I keep encountering 'Unexpected token' errors or strange outputs. The library I am using is jQuery. The data that nee ...

JavaScript error occurs when trying to iterate through a property that is undefined using a forEach method

I've encountered an issue with my JavaScript code. Every time I try to run it, I get the error message 'Error: TypeError: Cannot read property 'forEach' of undefined'. Could someone kindly explain why this is happening and offer a ...

Tips for identifying the highest number of repeating "values" in a JavaScript array

My problem is similar to the question asked here: Extracting the most duplicate value from an array in JavaScript (with jQuery) I tried the code provided, but it only returns one value, which is 200. var arr = [100,100,200,200,200,300,300,300,400,400,4 ...

I am no longer able to connect to mySQL using node js

I recently upgraded my node version, and now I'm facing issues accessing my database through my application. I have tried various solutions such as: - Changing the route to 127.0.0.1. - Adding my port number 3306. - Including socketPath: '/Applic ...

Struggling to retrieve the tagName attribute when clicking in JavaScript

I am trying to extract the tagName of any element within an iframe when it is clicked. Unfortunately, my JavaScript code is not working as expected. As a beginner in JavaScript, I would appreciate some guidance on where I might be going wrong. <div cl ...

Sorting tables in Vue.js with Buefy components for a user-friendly experience

In my current project, I am utilizing Vue.js. The majority of the tables I am working with use Buefy's built-in sorting feature, which I find to be the simplest solution. You can find more details in the documentation here: <template> < ...

Creating a 3D Slicing Tool using Javascript and Three.js

I am currently working on a web application that utilizes three.js to estimate the cost of a 3D printing model, along with other functionalities. After successfully calculating the bounding box and volume of the object, I am now focusing on generating sli ...

What is the best way to execute a JavaScript function using Python Selenium?

Is it possible to repeatedly call the MapITRFtoWgs84() function with input from a text file and save the output to another text file? I believe Selenium might be the right tool for this task. Could you provide guidance on how to achieve this? Attached is ...

Assigning values to props in a Vue component

I created a Vue component that is supposed to receive the "uploadedFile" prop, but it's not functioning properly. I am only getting the correct information in the $attrs: https://i.sstatic.net/crXmH.png Here is my component: Vue.component('t ...

Guide to building a landscape in three.js

Creating a plane with numerous segments is the first step, but how do I go about adjusting the y position of the vertices afterwards? Appreciate your help in advance, ...

Show an input field in the view depending on a condition in AngularJS

[{id: "1", name: "first_name"}, {id: "2", name: "last_name"}, {id: "3", name: "city"}] <div ng-if="first_name"> <input type="text" name="first_name" ng-model="user.first_name"></div> <div ng-if="last_name"><input type="text" nam ...

What's the Hold-Up with IntersectionObserver in Brackets?

As a novice in the world of web development, I have been utilizing Brackets as my main tool. Recently, I've encountered a few hurdles specifically related to javascript. One issue I'm facing is trying to implement lazy loading on a div containing ...

The unspoken rules of exporting and importing in TypeScript

In comparison to Java (as well as other programming languages), TypeScript provides multiple options for exporting and importing entities such as classes, functions, etc. For instance, you have the ability to export numerous classes, constants, functions ...