Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
AngularJS Web application development Cookbook

You're reading from   AngularJS Web application development Cookbook Over 90 hands-on recipes to architect performant applications and implement best practices in AngularJS

Arrow left icon
Product type Paperback
Published in Dec 2014
Publisher Packt
ISBN-13 9781783283354
Length 346 pages
Edition 1st Edition
Arrow right icon
Author (1):
Arrow left icon
Matthew Frisbie Matthew Frisbie
Author Profile Icon Matthew Frisbie
Matthew Frisbie
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Maximizing AngularJS Directives FREE CHAPTER 2. Expanding Your Toolkit with Filters and Service Types 3. AngularJS Animations 4. Sculpting and Organizing your Application 5. Working with the Scope and Model 6. Testing in AngularJS 7. Screaming Fast AngularJS 8. Promises 9. What's New in AngularJS 1.3 10. AngularJS Hacks Index

Linking directives

For a large subset of the directives you will eventually build, the bulk of the heavy lifting will be done inside the directive's link function. This function is returned from the preceding compile function, and as seen in the previous recipe, it has the ability to manipulate the DOM in and around it.

How to do it…

The following directive will display NW, NE, SW, or SE depending on where the cursor is relative to it:

angular.module('myApp', [])
.directive('vectorText', function ($document) {
  return {
    template: '<span>{{ heading }}</span>',
    link: function (scope, el, attrs) {

      // initialize the css
      el.css({
        'float': 'left',
        'padding': attrs.buffer+"px"
      });

      // initialize the scope variable
      scope.heading = '';

      // set event listener and handler
      $document.on('mousemove', function (event) {
        // mousemove event does not start $digest,
        // scope.$apply does this manually
        scope.$apply(function () {
          if (event.pageY < 300) {
            scope.heading = 'N';
          } else {
            scope.heading = 'S';
          }
          if (event.pageX < 300) {
            scope.heading += 'W';
          } else {
            scope.heading += 'E';
          }
        });
      });
    }
  };
});

This directive will appear in the template as follows:

(index.html)

<div ng-app="myApp">
  <div buffer="300" 
       vector-text>
  </div>
</div>

How it works…

This directive has a lot more to wrap your head around. You can see that it has $document injected into it, as you need to define event listeners relevant to this directive all across $document. Here, a very simple template is defined, which would preferably be in its own file, but for the sake of simplicity, it is merely incorporated as a string.

This directive first initializes the element with some basic CSS in order to have the relevant anchor point somewhere you can move the cursor around fully. This value is taken from an element attribute in the same fashion it was used in the previous recipe.

Here, our directive is listening to a $document mousemove event, with a handler inside wrapped in the scope.$apply() wrapper. If you remove this scope.$apply() wrapper and test the directive, you will notice that while the handler code does execute, the DOM does not get updated. This is because the event that the application is listening for does not occur in the AngularJS context—it is merely a browser DOM event, which AngularJS does not listen for. In order to inform AngularJS that models might have been altered, you must utilize the scope.$apply() wrapper to trigger the update of the DOM.

With all of this, your cursor movement should constantly be invoking the event handler, and you should see a real-time description of your cursor's relative cardinal locality.

There's more…

In this directive, we have used the scope parameter for the first time. You might be wondering, "Which scope am I using? I haven't declared any specific scope anywhere else in the application." Recall that a directive will inherit a scope unless otherwise specified, and this recipe is no different. If you were to inject $rootScope to the directive and log to the $rootScope.heading console inside the event handler, you would see that this directive is writing to the heading attribute of the $rootScope of the entire application!

See also

  • The Isolate scope recipe goes into further details on directive scope management
You have been reading a chapter from
AngularJS Web application development Cookbook
Published in: Dec 2014
Publisher: Packt
ISBN-13: 9781783283354
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image