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,238 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 17, 2013 at 7:42 PM
HashKeyCopier - An AngularJS Utility Class For Merging Cached And Live Data
Ben - thanks so much for posting these Angular articles and findings, they've been a huge help towards learning one of the more 'complex' JavaScript frameworks out there (IMO). I have been using Angu ... read »
May 16, 2013 at 5:01 PM
UPDATE: Parsing CSV Data Files In ColdFusion With csvToArray()
Your code was the closest thing I've found to obtaining some direction for converting ISO fields to values that CF can translate properly. Thank you for posting! ... read »
May 15, 2013 at 10:37 PM
Very Simple Pusher And ColdFusion Powered Chat
hi id making plz easy ... read »
May 15, 2013 at 6:07 PM
Making SOAP Web Service Requests With ColdFusion And CFHTTP
Ben, you once again saved my bacon at work. Thank you, thank you, thank you! ... read »
May 15, 2013 at 4:15 PM
What If All User Interface (UI) Data Came In Reports?
@Josh, Thanks! @Ben, I definitely recommend the David West book "Object Thinking" I've been quoting from. It goes deeply into the philosophy and history of OO programming. His breadth ... read »
May 15, 2013 at 11:36 AM
Ask Ben: Print Part Of A Web Page With jQuery
I found this helpfull when you need to keep (refresh) the original parent page after closing the iframe child print dialog (Hoping you're not using a form at this time so it won't submit again): On ... read »
May 14, 2013 at 7:13 PM
What If All User Interface (UI) Data Came In Reports?
@Jonah, If there's any books you'd recommend on the subject of domain modelling, I'd love to hear it. I just downloaded the free PDF of "Domain Driven Design Quickly". Figured I'd give it ... read »
May 14, 2013 at 6:57 PM
The UX Of Prototyping: Low-Fidelity Is The New High-Fidelity
@Phillip, I'm not sure I follow what you mean? Are you saying that you looked at the list of widgets provided by the jQuery UI and let that be your style guide? ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools