AngularJS - Directives

adding useful behavior to element with directives

by Shashank Srivastava

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.13/angular.min.js"></script>
<div ng-app="myApp">
    <div enter="label" leave>This is an element</div>
</div>

CSS

.label {
    background: blue;
    color: white;
}

JavaScript

var myApp = angular.module('myApp', []);

myApp.directive('enter', function () {
    return function (scope, element, attrs) {
        element.bind("mouseenter", function() {
            element.addClass(attrs.enter);
        });
    };
});

myApp.directive('leave', function () {
    return function (scope, element, attrs) {
        element.bind("mouseleave", function() {
            element.removeClass(attrs.enter);
        });
    };
});