When using $scope.$emit
, it will only notify its parent scope
.
For example:
<div ng-controller="LihatKhsController">
<div ng-controller="KhsController">
</div>
</div>
JS
function KhsController($scope, $rootScope){
$scope.$emit('callkhs', {param:'test'});
}
function LihatKhsController($scope, $rootScope){
$scope.$on("callkhs", function(event, data){
console.log('hello callkhs', data.param); //will not show
});
}
In this scenario, KhsController
will trigger LihatKhsController
because LihatKhsController
is the parent of KhsController
.
If you use $scope.$broadcast
, it will notify its child.
For instance:
<div ng-controller="KhsController">
<div ng-controller="LihatKhsController">
</div>
</div>
JS
function KhsController($scope, $rootScope){
$scope.$emit('callkhs', {param:'test'});
}
function LihatKhsController($scope, $rootScope){
$scope.$on("callkhs", function(event, data){
console.log('hello callkhs', data.param); //will not show
});
}
In this case, KhsController
will trigger LihatKhsController
as KhsController
is the parent of LihatKhsController
.
Both methods do not take sibling controllers into consideration.
<div ng-controller="KhsController">
</div>
<div ng-controller="LihatKhsController">
</div>
$emit
and $broadcast
have slight differences in rootScope
.
Using $rootScope.$emit
will only notify on $rootScope.$on
.
While with $rootScope.$broadcast
, it will notify both $rootScope.$on
and all $scope.$on
.
For example:
function KhsController($scope, $rootScope){
$rootScope.$broadcast('callkhs', {param:'test'});
}
function LihatKhsController($scope, $rootScope){
$scope.$on("callkhs", function(event, data){
console.log('hello callkhs', data.param);
});
}