How two controllers can communicate between each other (Mini-Challenge 9)

Table of Content

Mini-Challenge 9

ng-challenge controllersAngularJs Mini-Challenges is a growing collection of "Challenges" about the most quirky parts of the AngularJs framework. It encourage you to find and fix common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert AngularJs programmers may encounter on their endeavours into the depths of the framework.

AngularJs Mini-Challenges does not aim to teach you AngularJs. Former knowledge of the Framework is strongly recommended in order to understand the topics covered in this Challenges. In order to learn the basics of the Framework, please head over to this excellent book:



Book Tip

ng-book - The Complete Book on AngularJS
Ready to master AngularJS? What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall?



The Challenge:

I have two controllers in an AngularJs application, I need to make a change to a variable in one controller and click a button that will going to talk to the second controller, lets suppose we have this in the View:

<div ng-controller="Ctrl1">
        <input type="text" ng-model="foo" />
        <input type="button" value="Talk to Ctrl2" ng-click="talkToCtrl2()" />
<div ng-controller="Ctrl2">{{foo}}</div>


And then we have this in the controllers:

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

myApp.controller('Ctrl1', myController);

myController.$inject = ['$scope']

function myController($scope) {
$ = "setted in ctrl1";
$scope.talkToCtrl2 = function () {
//Implement this function

myApp.controller('Ctrl2', myController2);

myController2.$inject = ['$scope']

function myController2($scope) {
$ = "setted in ctrl2";


The challenge for you is to implement the talkToCtrl2() function, so when you click the button the data in the input text get passed to Ctrl2 and gets printed in the view.
Here is a working example in jsFiddle:

Here you can find a possible solution

If you feel that the solution is poor or incomplete or there is room for improvement, please share with every one, you can leave a comment.