Leveraging angular.extend() with controllers and function overrides

Currently, I am working with Angular 1.4.8 and attempting to expand a controller. The original controller and the expanding controller are quite similar, but there is a specific function that I aim to replace in the extending controller.

angular.module('app').controller('ControllerOne', function() {

    var vm = this;

    vm.data = {};

    vm.callSayHello = function() {
        vm.sayHello();
    }

    vm.sayHello = function() {
        console.log('Hello from ControllerOne.');
    }
});

angular.module('app').controller('ControllerTwo', ['$scope', function($scope) {

    angular.extend(vm, $controller('OrdersAddController', { $scope: $scope }));

    // I don't want to override vm.callSayHello() so I'm not redefining that function.

    // Here's what I intend to override.
    vm.sayHello = function() {
        console.log('Hello from ControllerTwo.');

        // Some additional handling here.
    }
}]);

<button type="button" ng-click="ctrl.callSayHello()">Click Me</button>

It appears possible to override the functions of ControllerOne in ControllerTwo. However, in this scenario, the function I wish to override, vm.sayHello(), is not directly triggered by an event like a click, but instead, it is called by another function, vm.callSayHello().

The issue lies in the fact that when vm.callSayHello() is executed from either ControllerOne or ControllerTwo, it always invokes vm.sayHello() from

ControllerOne</code, regardless of being redefined in <code>ControllerTwo
.

I hope this explanation clarifies things. Is there a method to simply replace the vm.sayHello() function in ControllerTwo?

Answer №1

Here is a way to approach this:

function myFunc(vm, $scope) {
  // If no vm is provided, use 'this'
  vm.someFunction = ...
}

Then, you can implement it like this:

function baseController($scope) {
  var vm = this;
  myFunc(vm, $scope);
}

function extendedController($scope) {
  var vm = this;
  myFunc(vm, $scope);
  vm.someFunction = ... // Adding something new
}

However, a more elegant solution would be to avoid extending controllers altogether... If you have shared functions, consider using a service or a separate controller.

Answer №2

Utilizing JavaScript inheritance can be a beneficial approach for your project.

//defining controller 1
function ControllerOne() {
  this.data = {};
}

ControllerOne.prototype.callSayHello = function() {
  this.sayHello();
};

ControllerOne.prototype.sayHello = function() {
  console.log('Greetings from ControllerOne.');
};

ControllerOne.$inject = [];

//defining controller 2
function ControllerTwo($scope) {

}

ControllerTwo.prototype = Object.create(ControllerOne.prototype);

ControllerTwo.constructor = ControllerTwo;

ControllerTwo.prototype.sayHello = function() {
  console.log('Greetings from ControllerTwo.');
};

ControllerTwo.$inject = ['$scope'];

//angular controller setup
angular.module('app', [])
  .controller('ControllerOne', ControllerOne)
  .controller('ControllerTwo', ControllerTwo);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="ControllerOne as ctrl">
    <button type="button" ng-click="ctrl.callSayHello()">Click Me (Ctrl 1)</button>
  </div>
  <div ng-controller="ControllerTwo as ctrl">
    <button type="button" ng-click="ctrl.callSayHello()">Click Me (Ctrl 2)</button>
  </div>
</div>

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

Color in the diamond shape only to a designated height

I am in search of a unique diamond shape that allows me to fill the color up to a specific height based on an attribute or variable provided. https://i.stack.imgur.com/62U6h.png. I attempted creating the diamond shape and initially considered placing it ...

Highcharts - problem with chart width being fully rendered

I am currently using a Highcharts column chart and I am looking to make it a fully responsive chart with 100% width. The container for the chart is a simple <div> without any additional formatting. Upon document load, the chart remains at a fixed wid ...

Struggling to clear items from input field within AngularJS

I'm currently facing an issue where I am unable to delete data from an input field. var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl', function MyCtrl($scope) { $scope.items = [ { name: & ...

Handling Posts and Gets with Jquery/Javascript

Working on a web application that involves generating numerous post and get requests. I am able to monitor all the requests using Developer Tools in Mozilla/Chrome, as well as with Charles (an app). Is it feasible to develop a jQuery or JavaScript functi ...

Adjust the border hue of the MUI disabled outline input

I am currently struggling to locate the exact definition of this border color. After inspecting the dom, I cannot seem to find any border style within the input component or its pseudo elements... My main goal is to slightly lighten the color of the input ...

Error: The requested resource, youtube#videoListResponse, is currently unavailable

When attempting to access a YouTube playlist that includes private videos, the bot will encounter an error message. Error: unable to locate resource youtube#videoListResponse Below is the code snippet in question: if (url.match(/^https?:\/\/(w ...

Guide on setting a JSON object using the getJSON method

In my coding project, I am trying to assign values of lat and lng from a JSON object named branch to a variable called jsonData. When I use console.log to check jsonData.responseJSON.positions.length or jsonData.responseJSON.positions[0].lat, etc. I c ...

exploring alternatives to ng-container in angular-4.x for selecting elements

Currently in my Angular 4.x project, I have a component using the Selector 'abc' as shown below: @Component({ selector: "Abc", templateUrl: "Abc.html", styleUrls: [ "Abc.css" ] }) However, the "Abc" tag is also present in the DOM, b ...

What is the method for accessing the locale and messages of the IntlProvider within a component?

My index.js file includes the following code: import trFi from './translations/fi_FI.json'; import trSv from './translations/sv_SE.json'; ReactDOM.render( <IntlProvider locale={my_locale} messages={{ fi: trFi, sv: trSv } ...

Managing time-intensive web service operations using JavaScript callbacks

One of the operations in my Web application involves a function that returns a value, which then needs to be passed to a web service method running separately from the application. This web service operation takes some time to complete and therefore must r ...

Eliminate the need for index.html in the URL when using MVC WebApi

I am currently utilizing Angular for the front end and have an index.html page as the starting point. On the main page, the URL appears as follows: localhost:588/index.html#/ I desire it to appear as: localhost:3478/#/ or simply localhost:3478/ The iss ...

Creating unique border-radius for each point in a Highcharts column chart with React

Let's flip the script and start at the finish line. My goal is to customize my column chart to resemble this design: https://i.stack.imgur.com/FckJB.png Creating this style is a breeze with chart.js Credit: I've already delved into this inquiry ...

What is the best way to control the class name of elements using jQuery in an MVC4 application?

Among the <li> elements, one of them contains the class "current". Determining which <li> is the current one. View below: @{ int k = 10; //the value changes with each request } <ul class="car"> @foreach (var item in modelCoun ...

Tips for arranging alternating elements in a column layout using an array data model

In the $scope there is a dynamic array and in the HTML template, there are three columns. The goal is to render elements from the array in the HTML like this: <div class="first-column"> <div><!--element of (index + 3) % 3 === 0 will be pl ...

The functionality of two-way data binding seems to be failing when it comes to interacting with Knock

I am currently working on a piece of code that consists of two main functions. When 'Add more' is clicked, a new value is added to the observable array and a new text box is displayed on the UI. Upon clicking Save, the values in the text boxes ...

Exploring Angular 2 Beta 8: An Introduction to @Query Usage

My attempt to utilize @Query to fetch data regarding an element in my template has not been successful. I made an effort using the following approach: Referenced here. Here is a snippet of my code, import {Component, Query, QueryList, ElementRef} from &a ...

Error message in console: AngularJS throws an error saying 'No module found: uiCropper'

Hey there, I'm looking to add an image cropper to my webpage. I came across some code on Codepen, but when I tried using it, the code didn't work and I encountered this error https://i.sstatic.net/h5F4T.png angular.module('app', [&ap ...

Challenges with jQuery Image Sliders

Currently, I am learning from a tutorial on creating a custom jQuery content slider and you can find the tutorial here. Everything is working smoothly in terms of creating the image slider. However, I am facing an issue where I want to have the 'Next ...

Is it possible to store Socket.IO responses in a cache for quicker retrieval?

Consider this scenario where I have a websocket implementation shown below: let itemsArray = []; function fetchData() { itemsArray = await db.query(`SELECT * FROM Items`); } function emitData() { io.sockets.in("room_foo").emit("data", JSON.stringify ...

Sometimes the function setFromObject(mesh) returns inaccurate values

THREE.Box3.setFromObject(*object*) is returning inaccurate values. I will demonstrate my process in understanding this issue: I am creating 2 meshes using vertices. The first one using the triangle() function, and the other using trapezoidForm(). var tri ...