If you use $scope.$emit
, it'll notify only it's parent scope
.
Like this
<div ng-contoller="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('halo callkhs', data.param); //not show
});
}
Here KhsController
will trigger LihatKhsController
as LihatKhsController
is prent of KhsController
.
If you use $scope.$broadcast
, it'll notify it's child
Like this
<div ng-contoller="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('halo callkhs', data.param); //not show
});
}
Here KhsController
will trigger LihatKhsController
as KhsController
is parent of LihatKhsController
.
Both of them won't consider siblings controller Like
<div ng-contoller="KhsController">
</div>
<div ng-controller="LihatKhsController">
</div>
$emit
and $broadcast
is slightly different in rootScope
.
If you use $rootScope.$emit
, it'll only notify on $rootScope.$on
.
If you use $rootScope.$broadcast
,it'll not only notify on $rootScope.$on
but also all $scope.$on
.
Like this
function KhsController($scope, $rootScope){
$rootScope.$broadcast('callkhs', {param:'test'});
}
function LihatKhsController($scope, $rootScope){
$scope.$on("callkhs", function(event, data){
console.log('halo callkhs', data.param);
});
}