I try to call function while emit data from one controller to another in AngularJS. But it doesn't work for me in Angular v.1.2. I need to call ctrl1
function from ctrl2
. Anyone can give me some idea for this issue?
Sample code:
<div ng-contorller="ctrl">
<div ng-contorller="ctrl1">
</div>
<div ng-contorller="ctrl2">
</div>
</div>
function parentctrl(){
}
function ctrl1($scope){
$scope.callfn = function(){
console.log("success");
}
$scope.$on('emitdata', function(event, data){
$scope.callfn();
})
}
function ctrl2($scope){
$scope.$emit('emitdata', {'key':'uu'});
}
Or you could use both emits and broadcasts. Child scopes emits, parents broadcast. Like so: http://plnkr.co/edit/pjGIHByzkwCeNiaVrdb6?p=preview
app.controller("ctrl", function($scope) {
$scope.$on('emitdata', function(event, data) {
// This event will reach: ctrl -> ctrl1 + ctrl2
$scope.$broadcast('broadcast-data', data);
});
});
app.controller("ctrl1", function($scope) {
$scope.$on('broadcast-data', function(event, data) {
$scope.received = data;
})
});
app.controller("ctrl2", function($scope) {
$scope.emit = function() {
// This event will reach: ctrl2 -> ctrl -> rootScope
$scope.$emit('emitdata', {'key': 'uu'});
};
});
$emit
propagates events upwards, meaning that the emitting controller should be inside the listening controller.
<div ng-controller="ctrlone">
<div ng-controller="ctrltwo">
<!-- ctrltwo is the emitting controller
ctrlone is the listening controller -->
</div>
</div>
Now if there are two controllers that are on the same level like this:
<div ng-controller="parent">
<div ng-controller="ctrlone">
<!-- i listen for an event -->
</div>
<div ng-controller="ctrltwo">
<!-- i raise an event -->
</div>
</div>
There is no direct way for ctrlone
to communicate with ctrltwo
and vice versa. What you can do in this situation is to use $rootScope.$broadcast
instead of emit
:
function ctrltwo($rootScope) {
$rootScope.$broadcast('myEvent', {'key':'uu'});
}
function ctrlone($scope) {
$scope.$on('myEvent', function(event, data){
$scope.callfn();
});
}
You can also use $scope.$parent
instead of $rootScope
, but be careful when doing this, because this may stop working if the controller nesting changes.
This is how ctrl2 function should look:
function ctrl2($scope, $rootScope) {
$rootScope.$broadcast('emitdata', {'key':'uu'});
}
$emit is to send up, $broadcast is to send down. $rootScope is at the top.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.