Get angular modules to talk to anything

Lately we’ve started building more and more modules that were meant to integrate within some unknown application.  By unknown, I mean that we could not tell the version of angularjs nor if there will be angularjs inside.

When your app lives “inside” angular, it’s pretty easy to create beautiful API’s that are based on the binding made possible with directives (as shown in this post).

But what if the hosting app was built using some other framework (or even using vanilla js)?

I’ve found a nice implementation of the mediator design pattern.  In short, it is a pub-sub pattern, which makes your app communicate in an event-driven manner.  The library is called mediatorjs and it made my life super simple (I could have built the whole interface using promises etc., but why if it’s already here?).

I’ve created a small demo demonstrating this approach:

Looking at the code, you can see two parts of the app.  The non angular part and the angular part.  The app is doing something very basic – on an “angular” click it sends a message outside of angular and vice versa. On each such message, the button color changes.  So if I click inside angular, the external button will change color and vice versa.

This isn’t much of an API, but this can be easily extended into one.  Just create a small script (that would look a little bit like an angular service…) that will expose these methods. Here’s an example:

In the above example, I’ve created a simple API for the click and the type event. You can see an alert message when clicking the angular button, as well as see what you type in the angular input element in the non angular input element.

This method could be easily used in order to create a general API so we could still develop with angular (for fast delivery) for non angular apps.

2 thoughts on “Get angular modules to talk to anything

  1. ram

    Nice tool!
    Could it help when we have different versions of angular?
    Was mediator checked for performance?

    • Yonatan

      Meidator is a very old and unmaintained plugin. I’ve used it here because it was one of the first JS examples for this Design Pattern. I would suggest taking Event Emitter 3 at the moment, in order to implement this method.

Leave a Reply