Check out Mini-challenge 9 Instructions
Answer:
There are several ways that one controllers can talk to another, This google group thread, http://groups.google.com/d/topic/angular/m_mn-8gnNt4/discussion, discusses 5 ways controllers can talk to each other.
1. Shared service.
2. Events.
3. Prudent pragmatic use of $root scope.
4. Watchers.
And a 5th - scope prototypical inheritance?
http://docs.angularjs.org/guide/scope
For a sake of simplicity we are going to show a possible answer to this challenge with Events, using $broadcasting and $on:
This is the view:
<div> <div ng-controller="Ctrl1"> <input type="text" ng-model="foo" /> <input type="button" value="Talk to Ctrl2" ng-click="talkToCtrl2()" /> </div> <div ng-controller="Ctrl2">{{foo}}</div> </div>
And this is the javascript:
var myApp = angular.module('myApp', []); myApp.controller('Ctrl1', myController); myController.$inject = ['$scope', '$rootScope'] function myController($scope, $rootScope) { $scope.foo = "setted in ctrl1"; $scope.talkToCtrl2 = function () { $rootScope.$broadcast('emitedFromController1', $scope.foo); } }; myApp.controller('Ctrl2', myController2); myController2.$inject = ['$scope'] function myController2($scope) { $scope.foo = "setted in ctrl2"; $scope.$on('emitedFromController1', function(event, args) { $scope.foo = args; }); };
In the talkToCtrl2 function we can implement $rootScope.$broadcast('emitedFromController1', $scope.foo); and then in the second controller we can implement:
$scope.$on('emitedFromController1', function(event, args) {
$scope.foo = args;
});
You can see a working example in this jsFiddle:
If you have a solution for this challenge, different from the proposed solution on this post, don't be shy and share it with us 🙂