I am creating a custom chart widget in angularjs using a directive with isolated scope. The idea being that each widget should be able to exist in isolation after receive basic config information on how to create itself.
The widget will communicate with other parts of the application by listening for an "update.data" event. When the event is triggered, the widget knows to refresh its data (Make a call to the server) based on new config information available to it, passed through the event object.
A sample widget created is as below
ng.directive('metricOverview', ['Report', function(Report) {
return {
restrict: 'EA',
//replace: true,
scope: {
title: '@',
metrics: '=',
report: '@'
},
templateUrl: 'scripts/widgets/metric-overview/metric-overview.html',
controller: function($scope, $element)
{
},
link: function(scope, element, attrs) {
scope.$on("update.data", function()
{
Report.overview({metric: scope.metric, report: scope.report})
.$promise.then(function(result) {
console.log(result);
$(document).trigger("chart.refresh", result);
});
});
}
};
}]);
My question is where is it most appropriate to trigger the "update.data" event. For example, when the page is loaded and the DOM is ready, I want this event to be triggered and all loaded widgets should be able to listen for it and update themselves. I cannot trigger the event on the rootScope since it isnt accessible within the directive's isolate scope.
Done a couple of research but bulk of what I found relied on the use of a global/parent scope which doesnt serve my purpose due to the isolated nature of the directives
What will be the best way to approach this?
Hi handle this scenario with an eventbus service that uses the rootscope and $emit so the event does not go down lots of child scopes. You could just inject this service into the directive and added an event listener.