• 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

7 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.

1
Danny
Danny
7 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()

2
Chris Skinner
Chris Skinner
6 years ago

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

0
kapil soni
kapil soni
4 years ago

Really nice sir…very nice and expalanation.

0
trackback
Angularjs Call Function From Another Controller? The 20 Detailed Answer - Brandiscrafts.com
1 month ago

[…] + Read More Here […]

0

Primary Sidebar

Popular

  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Waiting for an Element to Exist With JavaScript
  • Thoughts on the Flipper Zero
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • How To Paginate An Array In Javascript
  • Reliably waiting for network responses in Playwright
  • How To Mock uuid In Jest
  • How to Copy Files Using the Copy Webpack Plugin (without copying the entire folder structure)
  • Wild Natural Deodorant Review

Recent Comments

  • Dwayne on Is Asking Developers How to Write FizzBuzz Outdated?
  • kevmeister68 on Is Asking Developers How to Write FizzBuzz Outdated?
  • Kevmeister68 on Start-Ups and Companies That Embrace Work From Anywhere Will Be More Likely to Survive the Coming Recession in 2023
  • kevmeister68 on What Would Get People Back Into the Office?
  • Dwayne on PHP Will Not Die

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz