Basic Directive Functionality

Let’s go over creating some basic behaviors. We’ll start by creating another app called “functionalities” with no dependencies, and then we’ll create two directives here: one for the behavior of mouse rolling over the element, and one for the mouse leaving the element.

If you don’t specify the restriction for a directive, it will default to “A”. In addition, if all we’re going to do the directive is use the linking function, we can use the shorthand of just returning the linking function instead of returning an object with the properties defined on it.

angular.module('functionalities', [])
.directive("entering", function(){
 return function() { }
})

Inside the linking function we get a few things to work with our element, for now we’ll only worry about scope and element. On the element, we’ll bind “mouseenter”, and log “Mouse has entered the div” to the console.

angular.module('functionalities', [])
.directive("entering", function(){
 return function(scope, element) {
      element.bind("mouseenter", function(){
        console.log("Mouse has entered the div");
      })
    }
})

Now we’ll create our app that’s named “functionalities” with a div and some content, and give the div the “entering” attribute from the directive we made.

  <body ng-app="functionalities">
    <div entering>Hover over me for fun times</div>
  </body>

When we load the page, once we mouse over the content we can see that it logs “Mouse has entered the div” each time because it’s bound to “mouseenter” event.

Now, we can duplicate the “entering” directive and rename it to a “leaving” directive, and change the logged text to “Mouse has left the div”

angular.module('functionalities', [])
.directive("entering", function(){
 return function(scope, element) {
      element.bind("mouseenter", function(){
        console.log("Mouse has entered the div");
      })
    }
})

.directive("leaving", function(){
 return function(scope, element) {
      element.bind("mouseleave", function(){
        console.log("Mouse has left the div");
      })
    }
});

Now we just need to add the leaving attribute to the div

  <body ng-app="functionalities">
  <div entering leaving>Hover over me for fun times</div>
  </body>

When we refresh the page and mouse over and leave, we can see that it now also logs “Mouse has left the div” to the console when your mouse leaves the content. This is how you set up a basic functionality which is the most common use case for directives, which is why you can do this shorthand of just returning the linking function.