This represents the structure of my page.
// app.html
<wrapper ng-if="initialized && $root.user.type!='guest'">
<header-component></header-component>
<div class="app-body">
<sidebar-component></sidebar-component>
<main class="main-content" style="height:{{$root.pageHeight}}px; overflow-y: scroll">
<ng-view></ng-view>
</main>
<aside-component></aside-component>
</div>
</wrapper>
Within the ng-view directive, I have a controller that needs to send data to the header-component. It is not directly associated with the header-component.
Consider the current controller for ng-view:
// some-screen.js
$scope.foo = "bar";
I want to display bar
in the header.
This can be achieved using either $rootScope (without an event) or by utilizing the $broadcast event.
First method - utilizing $rootScope directly:
// some-screen.js
$rootScope.foo = "bar";
// header.js
app.directive("headerComponent", ($rootScope) => {
return {
templateUrl: "/structure/header/header.html",
scope: {},
link: function($scope, element, attrs) {
console.log($rootScope.foo) // "bar"
}
}
});
Second method - employing the $broadcast event:
// some-screen.js
$rootScope.$emit("SomeNameOfTheEvent", $scope.foo);
// header.js
app.directive("headerComponent", ($rootScope) => {
return {
templateUrl: "/structure/header/header.html",
scope: {},
link: function($scope, element, attrs) {
$rootScope.$on("SomeNameOfTheEvent", function(event, info) {
console.log(info.foo) // "bar"
});
}
}
});
When using the $broadcast event, take note of these two factors:
You must name each event - this can become cumbersome in larger applications as recalling specific event names may prove challenging. Generating documentation to reference these names is necessary for maintaining consistency.
Both methods achieve the same result - $broadcast simply involves more code implementation.
AngularJS introduced the $broadcast event for a reason - what am I overlooking?