67386

How to listen for a site-wide event in a directive with isolate scope

Question:

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?

Answer1:

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.

(function (angular) { 'use strict'; /** * @ngdoc service * @name coreModule.eventbus * @requires $rootScope * * @description * Provides a eventing mechanism when a user cna broadcast and subscribe to application wide events. */ angular.module('coreModule').factory('eventbus', [ '$rootScope', function ($rootScope) { /** * @ngdoc function * @name subscribe * @methodOf coreModule.eventbus * * @description * Subscribes a callback to the given application wide event * * @param {String} eventName The name of the event to subscribe to. * @param {Function} callback A callback which is fire when the event is raised. * @return {Function} A function tht can be called to unsubscrive to the event. */ var subscribe = function (eventName, callback) { return $rootScope.$on(eventName, callback); }, /** * @ngdoc function * @name broadcast * @methodOf coreModule.eventbus * * @description * Broadcasts the given event and data. * * @param {String} eventName The name of the event to broadcast. * @param {object} data A data object that will be passed along with the event. */ broadcast = function (eventName, data) { $rootScope.$emit(eventName, data); }; return { subscribe: subscribe, broadcast: broadcast }; } ]); }(angular));

Recommend

  • How to focus on a particular portion of an another html page when click on a button or link
  • Display informations about a bubble chart D3.js in AngularJS
  • Uncaught Reference Input is not defined- @Input() not working in Angular 2
  • Angular UI Router root named view template change from child view
  • AngularJs ng-repeat filtering by a deeper tier of data
  • Manage different base layouts in Angular2
  • Optional spaces and multiple alternatives in wl-pprint-extras
  • Incorrect behaviour when selecting chips in Angular Material
  • Enterprise Architect - Cancel Connectors Bridges
  • How to display attributed text in a UITextView with NSTextContainer and NSTextStorage
  • Adding new column to DataFrame with values dependent on index ref
  • Safari PHP form submission -file upload hangs
  • show popover on input validation in angularjs
  • How to add regEx in angular filter
  • Change attribute of custom directive
  • Angular page doesn't refresh after data is added or removed
  • Not able to display correct data in table -AngularJS
  • AWS-SES: Handling Bounces for Invalid ISPs
  • How to request unsampled report from Google Analytics Management API using Google Apps Script?
  • android Navigation Bar hiding and persantage of usable screen overlap
  • python: forcing relative imports to search from script file
  • Python 3.2.2, error(scripts to exe)
  • Function calls are not supported. Consider replacing the function or lambda with a reference to an e
  • SAXReader not re-ecape characters
  • Test if a set exists before trying to drop it
  • Checking free space on FTP server
  • Meteor helpers not available in Angular template
  • MongoDB in PHP using aggregate to group by _id is null not working
  • Display issues when we change from one jquery mobile page to another in firefox
  • How to extract text from Word files using C#?
  • To display the title for the current loaction in map in iphone
  • R: gsub and capture
  • AT Commands to Send SMS not working in Windows 8.1
  • trying to dynamically update Highchart column chart but series undefined
  • NSLayoutConstraint that would pin a view to the bottom edge of a superview
  • sending mail using smtp is too slow
  • Append folder name and increment by 1 using batch script
  • Busy indicator not showing up in wpf window [duplicate]
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?