I downloaded this pretty cool simple UI widget that allows me to select a color from a nice color palette.  In my continuing effort to learn Angular, I decided to open the code on GitHub and see how the events were being handled.

Oh wait, first the widget can be found on GitHub here:

https://github.com/buberdds/angular-bootstrap-colorpicker

So the widget documentation had a section on handling events that were fired off in the Angular services.  So I immediately though, oh how the hell do I even handle the events then? I am so used to jQuery events and listening to the DOM, it was a new topic I wanted to understand.  I find I can learn so much from other developer’s code, and this widget it no exception. Outside of the fact the widget is simple and easy to hook into my app (mind you I did have to fiddle with the CSS to get the color selector dialog to align to the top of the page correctly, perhaps some kind of CSS confusion/conflict), the code was very well written and I was able to learn some new things just from looking at the code.  I strongly urge you to open the code up from other people and you may find something in there where you say, oh I didn’t know you could do that??  I mean as a Full Stack Web Developer, I need to know a pile of things, so how much can we truly know at any given time???  None the less, back on topic 🙂

Ends up I found some code that calls the Angular $emit, basically firing an event based on some name.  In this widget’s case, it was firing on the custom event colorpicker-selected.  So now I sat there wondering, how on earth do I define the event in Angular to have this widget call me in a magical way.  Well ends up Angular has something called $on and since I was using the $scope on my controller, I simply created this kind of code in my custom controller:

$scope.$on('colorpicker-selected', function (evt, obj) {
   console.log("Event Emitted");
 });

This was very cool, I selected a color from the widget in my app, and it magically displayed the Event Emitted message.  The obj param will contain a JS custom object that contains the following information:

{
    name: '',
    value: ''
}

Learn more about $emit and $on in AngularJS, even handling is a great way to write nice tight modules with custom dynamic behaviors.

Thanks buberdds for creating this widget and giving me some new found knowledge.