How can I send my $scope
object from one controller to another using .$emit
and .$on
methods?
function firstCtrl($scop
You can call a service from your controller that returns a promise and then use it in your controller. And further use $emit
or $broadcast
to inform other controllers about it.
In my case, I had to make http calls through my service, so I did something like this :
function ParentController($scope, testService) {
testService.getList()
.then(function(data) {
$scope.list = testService.list;
})
.finally(function() {
$scope.$emit('listFetched');
})
function ChildController($scope, testService) {
$scope.$on('listFetched', function(event, data) {
// use the data accordingly
})
}
and my service looks like this
app.service('testService', ['$http', function($http) {
this.list = [];
this.getList = function() {
return $http.get(someUrl)
.then(function(response) {
if (typeof response.data === 'object') {
list = response.data.results;
return response.data;
} else {
// invalid response
return $q.reject(response.data);
}
}, function(response) {
// something went wrong
return $q.reject(response.data);
});
}
}])
Scope(s) can be used to propagate, dispatch event to the scope children or parent.
$emit - propagates the event to parent. $broadcast - propagates the event to children. $on - method to listen the events, propagated by $emit and $broadcast.
example index.html:
<div ng-app="appExample" ng-controller="EventCtrl">
Root(Parent) scope count: {{count}}
<div>
<button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
<button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button><br>
Childrent scope count: {{count}}
</div>
</div>
example app.js:
angular.module('appExample', [])
.controller('EventCtrl', ['$scope', function($scope) {
$scope.count = 0;
$scope.$on('MyEvent', function() {
$scope.count++;
});
}]);
Here u can test code: http://jsfiddle.net/zp6v0rut/41/
According to the angularjs event docs the receiving end should be containing arguments with a structure like
@params
-- {Object} event being the event object containing info on the event
-- {Object} args that are passed by the callee (Note that this can only be one so better to send in a dictionary object always)
$scope.$on('fooEvent', function (event, args) { console.log(args) });
From your code
Also if you are trying to get a shared piece of information to be available accross different controllers there is an another way to achieve that and that is angular services.Since the services are singletons information can be stored and fetched across controllers.Simply create getter and setter functions in that service, expose these functions, make global variables in the service and use them to store the info
How can I send my $scope object from one controller to another using .$emit and .$on methods?
You can send any object you want within the hierarchy of your app, including $scope.
Here is a quick idea about how broadcast and emit work.
Notice the nodes below; all nested within node 3. You use broadcast and emit when you have this scenario.
Note: The number of each node in this example is arbitrary; it could easily be the number one; the number two; or even the number 1,348. Each number is just an identifier for this example. The point of this example is to show nesting of Angular controllers/directives.
3
------------
| |
----- ------
1 | 2 |
--- --- --- ---
| | | | | | | |
Check out this tree. How do you answer the following questions?
Note: There are other ways to answer these questions, but here we'll discuss broadcast and emit. Also, when reading below text assume each number has it's own file (directive, controller) e.x. one.js, two.js, three.js.
How does node 1 speak to node 3?
In file one.js
scope.$emit('messageOne', someValue(s));
In file three.js - the uppermost node to all children nodes needed to communicate.
scope.$on('messageOne', someValue(s));
How does node 2 speak to node 3?
In file two.js
scope.$emit('messageTwo', someValue(s));
In file three.js - the uppermost node to all children nodes needed to communicate.
scope.$on('messageTwo', someValue(s));
How does node 3 speak to node 1 and/or node 2?
In file three.js - the uppermost node to all children nodes needed to communicate.
scope.$broadcast('messageThree', someValue(s));
In file one.js && two.js whichever file you want to catch the message or both.
scope.$on('messageThree', someValue(s));
How does node 2 speak to node 1?
In file two.js
scope.$emit('messageTwo', someValue(s));
In file three.js - the uppermost node to all children nodes needed to communicate.
scope.$on('messageTwo', function( event, data ){
scope.$broadcast( 'messageTwo', data );
});
In file one.js
scope.$on('messageTwo', someValue(s));
HOWEVER
When you have all these nested child nodes trying to communicate like this, you will quickly see many $on's, $broadcast's, and $emit's.
Here is what I like to do.
In the uppermost PARENT NODE ( 3 in this case... ), which may be your parent controller...
So, in file three.js
scope.$on('pushChangesToAllNodes', function( event, message ){
scope.$broadcast( message.name, message.data );
});
Now in any of the child nodes you only need to $emit the message or catch it using $on.
NOTE: It is normally quite easy to cross talk in one nested path without using $emit, $broadcast, or $on, which means most use cases are for when you are trying to get node 1 to communicate with node 2 or vice versa.
How does node 2 speak to node 1?
In file two.js
scope.$emit('pushChangesToAllNodes', sendNewChanges());
function sendNewChanges(){ // for some event.
return { name: 'talkToOne', data: [1,2,3] };
}
In file three.js - the uppermost node to all children nodes needed to communicate.
We already handled this one remember?
In file one.js
scope.$on('talkToOne', function( event, arrayOfNumbers ){
arrayOfNumbers.forEach(function(number){
console.log(number);
});
});
You will still need to use $on with each specific value you want to catch, but now you can create whatever you like in any of the nodes without having to worry about how to get the message across the parent node gap as we catch and broadcast the generic pushChangesToAllNodes.
Hope this helps...
This is my function:
$rootScope.$emit('setTitle', newVal.full_name);
$rootScope.$on('setTitle', function(event, title) {
if (scope.item)
scope.item.name = title;
else
scope.item = {name: title};
});
The Easiest way :
HTML
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="sendData();"> Send Data </button>
</div>
JavaScript
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $rootScope) {
function sendData($scope) {
var arrayData = ['sam','rumona','cubby'];
$rootScope.$emit('someEvent', arrayData);
}
});
app.controller('yourCtrl', function($scope, $rootScope) {
$rootScope.$on('someEvent', function(event, data) {
console.log(data);
});
});
</script>