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
Module & Controller
Define a module and a controller with scope methods.
Scope Inheritance
Prototypal scope inheritance between parent and child controllers.
Services & Factories
Factory and service singletons for shared state and logic.
Routing (ngRoute)
Configure routes with templates, controllers, and resolve guards.
Custom Filters
Chainable filters for formatting values in templates.
Forms & Validation
Form with required, minlength, email validation, and disabled submit.