Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at CFUNITED 2010 (Landsdown, VA) with:

Exposing A Mouse Service For Click Events In AngularJS

By Ben Nadel on

Yesterday, I looked at creating an AngularJS directive in order to capture the click-event on the Document node. This required the underlying jQuery event object to be passed into the $scope of the given directive. While this worked, exposing the event object could be seen as letting the DOM (Document Object Model) leak into the Controller, where it is not supposed to be. As such, I wanted to quickly refactor yesterday's demo to communicate the click event through an intermediary Mouse service object.


 
 
 

 
  
 
 
 

There's absolutely nothing wrong with knowing about the DOM and about the UI events. The only constraint imposed by the MVC (Model-View-Controller) architecture is that the UI logic should be in a Directive (or a View), not in a Controller. So, rather than exposing the click event, what I'm going to do is create a Mouse service that stores an arbitrary location. This Mouse service can then be injected (via Angular's Dependency Injection mechanism) into both the Controller and the bnDocumentClick Directive. There, the Mouse service can then act as the vessel in which location-relevant data will be shared.

The Mouse service is super simple. It encapsulates an (X,Y) coordinate and exposes two methods for getting and setting the location. When the Directive captures the click event, it updates the Mouse location. When the Controller responds to the click event, it reads this new location from the shared Mouse service.

  • <!doctype html>
  • <html ng-app="Demo">
  • <head>
  • <meta charset="utf-8" />
  • <title>Sharing A Mouse Service In AngularJS</title>
  • </head>
  • <body
  • ng-controller="DemoController"
  • bn-document-click="handleClick()">
  •  
  • <h1>
  • Sharing A Mouse Service In AngularJS
  • </h1>
  •  
  • <p>
  • Click anywhere to trigger an event.
  • </p>
  •  
  • <p>
  • <strong>Click X</strong>: {{ mouseX }}
  • </p>
  •  
  • <p>
  • <strong>Click Y</strong>: {{ mouseY }}
  • </p>
  •  
  •  
  •  
  • <!--
  • Load jQuery and AngularJS from the CDN. In order for
  • AngularJS to use the "full" jQuery (as opposed to its own
  • jQLite), we need to load jQuery first.
  • -->
  • <script
  • type="text/javascript"
  • src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js">
  • </script>
  • <script
  • type="text/javascript"
  • src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js">
  • </script>
  • <script type="text/javascript">
  •  
  •  
  • // Create an application module for our demo.
  • var Demo = angular.module( "Demo", [] );
  •  
  •  
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  •  
  •  
  • // Define the mouse service to keep track of the mouse
  • // coordinates during mouse events. This doesn't actually
  • // track events; but, it provides a global access point for
  • // data that may come out of an event.
  • Demo.factory(
  • "mouse",
  • function() {
  •  
  • // Define the initial position. This will be a hash
  • // with X / Y properties.
  • var location = null;
  •  
  • // Let's keep track of the previous location, if it
  • // is going to be intertesting at all.
  • var previousLocation = null;
  •  
  • // Define the public API for this service.
  • var api = {
  •  
  • // Get the current location, if there is one.
  • getLocation: function() {
  •  
  • // Return a copy of the location so that we
  • // don't accidentally break encapsulation.
  • return(
  • angular.copy( location )
  • );
  • },
  •  
  • // I set the new location.
  • setLocation: function( x, y ) {
  •  
  • // If we have a current location, let's copy
  • // it into the previous location.
  • if ( location ) {
  •  
  • previousLocation = location;
  •  
  • }
  •  
  • // Overwrite with the new location.
  • location = {
  • x: x,
  • y: y
  • };
  •  
  • }
  •  
  • };
  •  
  • // Return the API as our factory definition.
  • return( api );
  •  
  • }
  • );
  •  
  •  
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  •  
  •  
  • // Define our document-click directive. This will evaluate the
  • // given expression on the containing scope when the click
  • // event is triggered.
  • Demo.directive(
  • "bnDocumentClick",
  • function( $document, mouse ){
  •  
  • // I connect the Angular context to the DOM events.
  • var linkFunction = function( $scope, $element, $attributes ){
  •  
  • // Get the expression we want to evaluate on the
  • // scope when the document is clicked.
  • var scopeExpression = $attributes.bnDocumentClick;
  •  
  • // Bind to the document click event.
  • $document.on(
  • "click",
  • function( event ){
  •  
  • // Set the click coordinates in the mouse
  • // service.
  • mouse.setLocation(
  • event.pageX,
  • event.pageY
  • );
  •  
  • // Apply the scope expression so the
  • // handler is invoked and the digest()
  • // method is invoked implicitly.
  • $scope.$apply( scopeExpression );
  •  
  • }
  • );
  •  
  • // TODO: Listen for "$destroy" event to remove
  • // the event binding when the parent controller
  • // is removed from the rendered document.
  •  
  • };
  •  
  • // Return the linking function.
  • return( linkFunction );
  •  
  • }
  • );
  •  
  •  
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  •  
  •  
  • // I am the controller for the Body tag.
  • Demo.controller(
  • "DemoController",
  • function( $scope, mouse ) {
  •  
  • // Set the initial X/Y values.
  • $scope.mouseX = "N/A";
  • $scope.mouseY = "N/A";
  •  
  • // When the document is clicked, it will invoke
  • // this method, passing-through the jQuery event.
  • $scope.handleClick = function(){
  •  
  • // Get the mouse location that has been updated
  • // as result of the click event.
  • var mouseLocation = mouse.getLocation();
  •  
  • $scope.mouseX = mouseLocation.x;
  • $scope.mouseY = mouseLocation.y;
  •  
  • };
  •  
  • }
  • );
  •  
  •  
  • // -------------------------------------------------- //
  • // -------------------------------------------------- //
  •  
  •  
  • </script>
  •  
  • </body>
  • </html>

As you can see, the "mouse" service is defined a dependency to both the Controller and the bnDocumentClick directive. The Controller then uses this service, instead of the underlying jQuery event object, to gather mouse location data. And, in a way, this makes a lot more sense. Before, when we were exposing the event object, we were exposing a lot of superfluous information. Now, we expose only the information that actually matters.

In this case, the Mouse service is a bit of a misnomer since it only contains information for document-level clicks - none of the other mouse-related AngularJS Directives (ex. ngMousemove) will update this service. That said, this was more of an exploration of using shared Service objects to expose data and less an exploration of capturing click events. It seems that this is the "Angular way": using Service objects to communicate across various aspects of the application.




Reader Comments

@Romain,

Thanks my man. Definitely, without a doubt, Directives are the hardest thing for me to wrap my head around. I actually spent about 5 hours today working on a directive that involved Plupload to do drag-n-drop file uploads. A lot of trial and error and trying to understand how $scopes interact with directives and isolation and what not.

Slowly, it's starting to make more sense.

Just trying to outline the diff between your previous post and the present one is

  • bn-document-click="handleClick( $event )"

this became this

  • bn-document-click="handleClick()"

. And the mouse location is handled via a service called 'mouse', to keep the controller not be aware of the event object.

@Rajkamal,

It's been a while since I looked at this code, but I believe you are correct. In the first approach, the $event was passed directly into the Controller via the click-directive. In the latter approach, rather than passing in the $event object, I'm updating a separate Mouse service, which is then consumed by the Controller.

I don't like the idea of passing the $event object into the Controller - it feels like something that's not supposed to be there. As I have gotten more into AngularJS, I strongly feel that whatever I was *going* to do with $event, should probably be handled inside a custom Directive that can capture the event on the DOM and then pipe it into the Controller.

Recently, I tried to codify my feelings about how many directives should work:

http://www.bennadel.com/blog/2476-My-Approach-To-Building-AngularJS-Directives-That-Bind-To-JavaScript-Events.htm