Exposing A Mouse Service For Click Events In AngularJS

Posted September 18, 2012 at 10:01 AM by Ben Nadel

Tags: Javascript / DHTML

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

Oct 26, 2012 at 5:34 PM // reply »
1 Comments

Thanks Ben! Your demo is clean, angular-oriented, and useful.

Regards,
Romain


Oct 27, 2012 at 5:18 PM // reply »
11,241 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.


Feb 26, 2013 at 3:42 PM // reply »
6 Comments

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.


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 22, 2013 at 4:43 AM
How Do You Use The ColdFusion CFParam Tag?
'<cfparam>' or 'isDefined()and <cfset>' performs the same task.Is there any difference? ... read »
May 21, 2013 at 7:46 PM
Using Plupload For Drag & Drop File Uploads In ColdFusion
No luck. At least I have uncovered the cause, URLScan 3.1. Here is what I see in the IIS log when a file is over 30mb. 2013-05-21 23:29:05 10.105.45.128 GET /plupload/assets/jquery/jquery-1.8. ... read »
May 21, 2013 at 6:12 PM
Using Plupload For Drag & Drop File Uploads In ColdFusion
Ben, I did not see you after Pete Freitag's Lockdown session at cfObjective but he said that IIS sets file size limits at 30MB by default which just happened to be the threshold for file size when ... read »
May 21, 2013 at 11:51 AM
Ask Ben: Parsing Very Large XML Documents In ColdFusion
Looking at my first ever XML document that I have to parse and put into MS SQL 2000 with CF8. I get it to list the desired Field name, many times over, and have a long list of this field name displa ... read »
May 21, 2013 at 9:25 AM
Turning Off and On Identity Column in SQL Server
you are awesome..i am lucky to get this blog between such a garbage one....Thanks, Prashant ... read »
May 20, 2013 at 4:38 PM
Using A Dynamic Column Name With ValueList() In ColdFusion
@Dana, Your confusion is well founded, since this is a very confusing features. In fact, it ONLY works if you use array notation. Meaning, that this: arrayToList( query[ "columnName" ] ) ... read »
May 20, 2013 at 4:34 PM
Using A Dynamic Column Name With ValueList() In ColdFusion
I was thinking chicken and the egg, I wouldn't have expected it to work in the valuelist going in I guess. Maybe I just need a beer, long day :) ... read »
May 20, 2013 at 4:29 PM
Using A Dynamic Column Name With ValueList() In ColdFusion
@Dana, That's if you're trying to reference a specific row. In this case, we're trying to reference the entire query column as one cohesive value. So, you are correct that if you wanted to output a ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools