portfolio | contact
June
Friday the 26th

Moving to angular, one piece at a time.

Friday, 4:18 PM
I'm currently in the process of of moving a massive ecommerce application from jQuery to angular. Since nearly everything depends on everything else, it becomes necessary for our new angular components to speak to the legacy jQuery code, and vice versa. I've written a few convenience methods you may find useful.

EDIT: so in practice, these work great! however, they don't trigger Angular's internal digest cycle. you'll likely want to write a convenience method that does that for you after issuing a message, or leveraging a service from within Angular. Such a method would look very similar to broadcastAngularEvent, except you'd only need a single argument (app), and once the appScope is found, you'd appScope.$apply()

// function for communicating with angular apps from outside angular.
function broadcastAngularEvent( app, message, messageData ){
var x, appScope, appSelector, selectors = [
'ng-app',
'ng_app',
'data-ng-app',
'x-ng-app' ];
for( x in selectors ){
appSelector = "*[" + selectors[x] + "=" + app + "]";
appScope = angular.element(document.querySelector(appSelector)).scope();
if( !!appScope ){ return appScope.$broadcast(message, messageData) }
}
}

// get and use Angular services from legacy code
function getAngularService( app, service ){
var x, appInjector, appSelector, selectors = [
'ng-app',
'ng_app',
'data-ng-app',
'x-ng-app' ];
for( x in selectors ){
appSelector = "*[" + selectors[x] + "=" + app + "]";
appInjector = angular.element(document.querySelector(appSelector)).injector();
if( !!appInjector ){ return appInjector.get( service )}
}
}

// broadcast events from within angular that jQuery code can consume.
function legacyBroadcast( eventName, eventData ){
var legacyEvent = document.createEvent('HTMLEvents');
legacyEvent.initEvent(eventName, true, true);
legacyEvent.eventData = eventData;
$window.dispatchEvent( legacyEvent );
}

/* catch these events like:
window.addEventListener('MY_EVENT', function( eventObject ) {
alert( eventObject.eventData );
});
*/

◄ back