Skip to content
AngularJS

Custom Directives

Attribute directive and element directive with isolated scope.

By EZ4Code Team
angularjsdirectivereusable

Code

angular.module('directivesApp', [])
.directive('highlight', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.on('mouseenter', function() {
        element.css('background', 'yellow');
      });
      element.on('mouseleave', function() {
        element.css('background', '');
      });
    }
  };
})
.directive('userInfo', function() {
  return {
    restrict: 'E',
    scope: { name: '@', age: '=' },
    template: '<div class="user"><b>{{ name }}</b> ({{ age }})</div>'
  };
});

<!-- Usage -->
<div highlight>Hover me</div>
<user-info name="Alice" age="30"></user-info>
<user-info name="Bob" age="{{ 25 }}"></user-info>

Explanation

Directives extend HTML with reusable behavior; restrict:'A' matches attributes, 'E' matches elements. The link function runs DOM logic (events, styling) while template provides HTML. Isolated scope (scope:{...}) prevents the directive polluting its parent: '@' binds a string, '=' two-way binds, '&' binds an expression.

More AngularJS Snippets