Using Angular to call a method in the parent controller from an inherited controller

I've been trying to figure this out for days with no success. I have a BaseController with an init method, among other things. I want to extend this controller and call the parent's 'init' method from the child's 'init' method.

The usual solution is to use

$scope.$parent.init($settings_object)
. However, this is throwing an error:
Error: $scope.$parent.init is not a function
.

Normally, the extended controller works fine and can access the parent's function and settings without any issues. It's just in this particular case that calling the same parent method from the child fails.

BaseController

(function( ){
var mainApp = angular.module("MyAppModule");      
mainApp.controller('BaseController',function($scope, $rootScope,GLOBAL_CONFIG, ajaxRESTful,sharedValues, messageDisplay) { //base contorller
      var bvm = this; //base vm

      this.init = function($settings_object){
      var keys = Object.keys($settings_object);
      for(i=0;i<keys.length;i++){
      bvm[keys[i]] = $settings_object[keys[i]];
      
      }
      }
      
          //code remved to keep simple
     
});
})();

Extended controller

(function( ){
var app = angular.module('MyAppModule');
app.controller('RoleEdit', function($scope, $rootScope,$controller) {
angular.merge(this, $controller('BaseController', {$scope: $scope}));
var vm = this;
vm.newRoleFormData = [];
vm.role_id = null; 
vm.mode = 'create';
vm.role = null;

vm.init = function ($object) {
console.log(vm);
console.log($scope.$parent);
$scope.$parent.init($object);
            if(vm.role_id != null){
              vm.loadInRole( );
            }
    };



}) //end contoller

})();//end of app

Why isn't this working? Is there a more efficient way to achieve this?

Answer №1

The `this` object in the controller and the `$scope` object are not directly connected. There is no automatic linking between them. Accessing `$scope.$parent` does not give you the controller, but rather the parent scope. Additionally, since you defined your parent method in `this.init` instead of the usual `$scope.init`, you won't be able to access it through scopes.

There are several ways to work around this issue, but as others have recommended, if you need functionality that is shared across multiple controllers, consider placing it in a service. Perhaps your `BaseController` itself should be a service.

Answer №2

Here is a suggestion for you to consider:

let originalInitialization = this.init.bind(this);
this.init = function ($element) {
  originalInitialization($element);
  if(vm.role_id !== null){
    vm.loadInRole();
  }
}

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

Having trouble accessing news feed with jQuery due to an unexpected token error when attempting to cross domains

I am attempting to access the Yahoo News feed from a SharePoint site, but it is causing a cross-domain access issue. Despite trying various solutions found on numerous websites and blogs, I still cannot resolve the problem. (I am executing this code in the ...

What is the most effective method for manipulating and slicing a string based on character matching?

In this particular scenario, we are dealing with strings that follow this pattern: CP1_ctl05_RCBPAThursdayStartTimePicker_0_dateInput CP1_ctl05_RCBPAFridayStartTimePicker_3_dateInput CP1_ctl05_RCBPAMondayStartTimePicker_1_dateInput The goal is to extract ...

Switching up icons using React Spring - a step-by-step guide!

Is it possible to change the icon when I click on it using react spring? For example, if I click on " ...

Getting information from MongoDB using Node.js and Angular

Currently, I am facing difficulty in retrieving data from MongoDB (I'm also using Mongoose) and sending it to Angular in order to populate the ng-repeat list with the retrieved data. I have managed to either display the data on a blank page directly f ...

Troubleshooting Problems with Loading Data into Highcharts using Javascript

The server is returning data in the following format: {"barData": [ {"Accepted":[0,0,0]}, {"Rejected":[0,0,0]}, {"In_Process":[0,1,0]}] } On the browser, it appears as follows: I initially thought that this was the correct st ...

Removing fragment identifier from the URL

If you go to stackoverflow.com/#_=_, the expression window.location.hash will display #_=_. All good so far. But when you run window.location.hash = '' to get rid of the hash, the URL changes to stackoverflow.com/#. (Note the unexpected # at the ...

The search for the view in the directory "/views" was unsuccessful in Express 4.0

I've been working on a project using Express 4.0 and the Express3-handlebars libraries for NodeJS. Below is the setup: app.set('views', path.join(__dirname, 'views/')); app.engine('hbs', hbs({defaultLayout: 'main&a ...

One-time PHP form submission only

On my website, I offer a variety of PDF download options. To access these downloads, I encourage visitors to sign up using a form. After signing up, they receive a direct link to the chosen PDF in their email. My goal is to streamline the process so that ...

What are the steps to integrate Material-UI Tabs with react-router?

I've been working on integrating Material-UI tabs with routing in my project. Although the routing is functioning well and displaying the selected tab, the smooth animation while navigating between tabs seems to be broken. How can I ensure that react ...

What is the best way to modify an Li element using the DOM in JavaScript?

Just the other day, I discovered how to use JavaScript and DOM to add and delete Li elements. Now I'm curious about how to edit those Li elements using DOM. Any suggestions? Thank you! ...

What could be causing anime.js to malfunction when clicked in Vue.js?

After implementing the mounted() function, the animation now successfully plays when the page is updated. However, there seems to be an issue as the animation does not trigger when clicked. Even though console.log registers a click event, the animation fa ...

Issues encountered while trying to integrate chessboard.js into a Vue application

I am facing an issue while trying to incorporate chessboard.js into my jetstream-vue application. Following the creation of the project, I executed the command npm install @chrisoakman/chessboardjs which successfully downloaded the package into my node_mod ...

Designing with AngularJS and ASP.Net Core

As someone new to web development, I am working on ASP.NET Core applications and looking to use their REST APIs in an AngularJS client-side setup. I have these applications with web interfaces and I want to integrate their REST APIs into my UI using Angula ...

How to send a parameter from an AngularJS controller to $stateProvider

Here is my AngularJS .config file that directs to the lead.html page when 'tasks' is activated from another HTML using ui-router: App .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterPr ...

Is there a way to optimize the re-rendering and redownloading of images files in map() when the useState changes? Perhaps we can consider using useMemo

This Chat application is designed with channels similar to the Slack App. Currently, I am utilizing a map() function for filtering within an array containing all channel data. The issue arises when switching between channels, resulting in re-rendering and ...

How is it possible that I am receiving two different outputs, with one of them even being undefined

I created a button using Jquery to submit POST data. It sends the value "name" : "kevin" in JSON format. $(document).ready(function() { $('#clickMe').on('click', function() { var data = {}; data.name="kevin"; ...

Retrieving text data from the JSON response received from the Aeris API

I am attempting to showcase the word "General" text on the HTML page using data from the API found under details.risk.type. The JSON Response Is As Follows... { "success": true, "error": null, "response": [ ...

Is there a way to prevent undefined properties when using .each in jQuery with a JSON object?

I am trying to populate the values of <inputs> on a webpage using data from a JSON object. http://codepen.io/jimmykup/pen/exAip?editors=101 To begin, I create a JSON object with two values - one for name and one for url. var jsonObj = []; var nam ...

The messageReactionAdd event has suddenly stopped functioning without any explanation

Currently, I am developing a Discord bot that assigns the role "Voteur" to a user when they react to an embed message created by the bot. Everything was functioning perfectly until recently, but for some reason, it has stopped working. The bot successfull ...

When working on a React/Redux application, how do you decide between explicitly passing down a prop or retrieving it from the global state using mapStateToProps?

As I embark on creating my inaugural React-Redux application, a recurring decision I face is whether to employ <PaginationBox perPage={perPage} /> or opt for <PaginationBox /> and then implement the following logic: function mapStateToProps({p ...