• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

AngularJS: How To Call A Controller From Another Controller

AngularJS · November 28, 2014

In AngularJS when it comes to communicating between controllers, one would naturally assume to reference another controller you can simply inject it into another controller and call its methods: however, you cannot do that.

Method 1: Shared service

One such method of communicating and sharing methods betweens multiple controllers is a shared service. Here you might put in a method for closing a overlay or redirecting the browser somewhere or checking the state and value of a variable.

The following example assumes you have created a service called “myService” and you have a method called updateVal and getVal for getting and setting values.

var myModule = angular.module('myapp', []);

myModule.controller('myController', ['$scope', 'myService', function ($scope, myService) {
    myService.updateVal('name', 'Dwayne');
}]);

myModule.controller('otherController', ['$scope', 'myService', function ($scope, myService) {
    if (myService.getVal('name') === 'Dwayne') {
        alert('The name is ' + myService.getVal('name'));
     } else {
         alert('There is no Dwayne');
     }
}]);

This is my preferred approach for sharing data and methods between controllers for a number of reasons; it makes things cleaner, it keeps logic separate from your controllers and above all: it makes things easier to test.

Method 2: Events

In some cases, events can be a lot cleaner than using a separate service. Triggering an event say for example when you open up an overlay, close it or perform some action you want to inform other controllers about can be done emitting an event on $scope.

var myModule = angular.module('myapp', []);

myModule.controller('myController', ['$scope', function ($scope) {
    $scope.$on('profile-updated', function(event, profileObj) {
        // profileObj contains; name, country and email from emitted event
    });
}]);

myModule.controller('otherController', ['$scope', function ($scope) {
    $scope.$emit('profile-updated', {
        name: 'Dwayne',
        country: 'Australia',
        email: 'somedude@example.com'
    });
}]);

Conclusion

Pick whichever feels right. I personally prefer method 1 because as I mentioned, it is testable, it is cleaner and keeps things separate. But using events also have their advantages as well.

Dwayne

Leave a Reply Cancel reply

6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
rishi raj sahu
rishi raj sahu
7 years ago

nice and easy example.. !!

0
Greg Walters
Greg Walters
7 years ago

Great explanation, the best I found. I am trying to use method 1, however, I’m having a timing issue where the otherController is calling getVal() before myController calls updateVal().

My page is a partial using myController and a section within the partial using otherController. I need to pass some data (retrieved via REST service) from myController to otherController, which enables otherController to populate some related data to myController’s data.

Would method 2 be a better option here, or am I missing something to make the service work?
Thanks.

0
Danny
Danny
6 years ago

You have an exposed code on the footer of your site, looks like Google Analytics

0
parthiban
parthiban
6 years ago

one controller in one js file another file at another js file how to communicate.
For eg :
i have created common.js file have call to db and get data(getStudDet()) one more controller for click event (submitform) how to call from click event to getstudDet()

0
Chris Skinner
Chris Skinner
6 years ago

Good stuff man. Well explained! +1..!

0
kapil soni
kapil soni
3 years ago

Really nice sir…very nice and expalanation.

0

Primary Sidebar

Popular

  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Which Neural DSP Archetype Plugins Should You Buy?
  • Smoke Detector Randomly Goes Off Early Hours of The Morning
  • How To Mock uuid In Jest
  • Neural DSP Reveal Details About the Long-Awaited Quad Cortex Desktop Editor
  • Web 3.0 may have died before it even started
  • Deno Raises $21M - but is anyone using it yet?
  • NBN Box Installed Inside of Garage, Where Do You Put The Modem?
  • How To Install Eufy Security Cameras Without Drilling or Using Screws

Recent Comments

  • Jay on Neural DSP Reveal Details About the Long-Awaited Quad Cortex Desktop Editor
  • john on Deno Raises $21M – but is anyone using it yet?
  • Oranges on How To Store Users In Firestore Using Firebase Authentication
  • Precious on Fixing Sequel Pro SQL Encoding Error For Imported SQL Files
  • James on A List of WordPress Gutenberg Core Blocks

Copyright © 2022 · Dwayne Charrington · Log in

wpDiscuz