- Angular JS Tutorial
- AngularJS Home
- AngularJS Introduction
- AngularJS Expressions
- AngularJS Directives
- AngularJS Modules
- AngularJS Controllers
- AngularJS Scopes
- AngularJS Data Binding
- AngularJS Services
- AngularJS HTTP
- AngularJS Filters
- AngularJS Forms
- AngularJS Validation
- AngularJS DOM Manipulation
- AngularJS Select
- AngularJS Tables
- AngularJS Events
- AngularJS Routing
- AngularJS Includes
- AngularJS Animations
- AngularJS Dependency Injection
- AngularJS API
- AngularJS Deployment
AngularJS Directives
AngularJS Directives are arguably the most powerful feature of the framework. They allow you to "teach" HTML new tricks by creating custom tags and attributes that have their own logic and behavior. In essence, a directive is a marker on a DOM element (like an attribute, element name, or CSS class) that tells AngularJS to attach a specific behavior to that element or even transform it entirely.
Introduction to Directives
Directives serve as the bridge between your JavaScript logic and your HTML view. Without them, HTML is just a static document; with them, it becomes a dynamic application. Directives allow you to:
- Bind data: Keep your UI in sync with your data models automatically.
- Manipulate the DOM: Change the structure of the page (adding/removing elements) based on application state.
- Extend HTML: Create complex UI widgets like date pickers, sliders, or graphs that look like native HTML elements.
Built-in Directives vs Custom Directives
- Built-in Directives: These are the "out-of-the-box" tools provided by AngularJS (prefixed with
ng-) to handle common tasks like loops, conditionals, and form handling. - Custom Directives: These are your own creations. You define the name, the template, and the logic, allowing you to build a domain-specific language for your project.
my- or app-). Never use ng-, as that is reserved for the framework and could lead to name collisions in future updates.
Core AngularJS Directives
ng-app Directive
This is the starting point of every AngularJS application. It designates the "root" element of the app (usually the <body> or <html> tag). Once the browser loads, AngularJS looks for this directive to bootstrap the application.
ng-init Directive
This directive allows you to initialize variables directly in your HTML. While handy for quick demos, it is generally discouraged for complex logic.
ng-init to handle business logic. Logic belongs in a Controller or a Service, not in your view. Use ng-init only for very simple tasks, like aliasing a property inside an ng-repeat.
ng-model Directive
The heart of "Two-Way Data Binding." It connects an input, select, or textarea to a property on the scope. If the user types in the input, the property updates; if the property updates via code, the input value changes automatically.
ng-repeat Directive
This acts like a foreach loop for your HTML. It clones the HTML element for every item in a collection (array or object).
ng-repeat with large lists, use the track by syntax (e.g., item in items track by item.id). This significantly improves rendering performance by helping AngularJS identify which specific items have changed.
ng-if Directive
This physically adds or removes an element from the DOM based on a condition. If the condition is false, the element doesn't exist in the page source at all.
ng-show and ng-hide Directives
ng-show: Uses the CSSdisplayproperty to show an element when a condition is true.ng-hide: Uses CSS to hide an element when a condition is true.
ng-if is "heavier" to toggle because it destroys and recreates DOM elements, but it's better for initial load. ng-show/hide is better for frequently toggled elements because the DOM stays intact, only the CSS changes.
ng-class Directive
Allows you to dynamically apply CSS classes. You can pass an object where the key is the class name and the value is a boolean condition (e.g., {'text-success': user.isActive}).
ng-style Directive
Works like ng-class, but for inline CSS styles. It's useful for dynamic styling like setting the width of a progress bar based on a percentage variable.
Form-related Directives
ng-submit Directive
Prevents the default browser form submission (which reloads the page) and allows you to call a JavaScript function instead.
ng-form Directive
In HTML, you cannot nest <form> tags. AngularJS provides ng-form to allow nested form validation logic, which is essential for complex, multi-step forms.
ng-disabled Directive
This is a lifesaver for UX. You can use it to disable a "Submit" button until the form is valid (e.g., ng-disabled="myForm.$invalid").
ng-checked Directive
Sets the checked attribute on checkboxes or radio buttons based on a scope expression. Note that if you use ng-model, you usually don't need ng-checked.
ng-readonly Directive
Makes an input field read-only dynamically. This is useful when you want to show data in a form field but only allow editing after the user clicks an "Edit" button.
Event Directives
Directives like ng-click, ng-dblclick, ng-mouseover, and ng-keyup allow you to capture user interactions. Unlike standard HTML event attributes (like onclick), these directives execute expressions within the AngularJS scope, meaning they have direct access to your variables and functions.
ng-click="total = price + tax; alert(total)", call a function in your controller: ng-click="calculateTotal()".
Custom Directives
Creating Custom Directives
You define custom directives using the .directive() method on your module. When naming your directive, use camelCase in JavaScript (myCustomerInfo), but call it using kebab-case in HTML (<my-customer-info></my-customer-info>).
Directive Scopes (Isolated Scope)
By default, directives share the scope of their parent. However, to build truly reusable components (like a reusable modal or slider), you should use an "Isolated Scope." This prevents the directive from accidentally messing with data in the rest of your app.
Directive Templates
The template property allows you to define the HTML structure that the directive will inject. For larger chunks of HTML, use templateUrl to point to an external .html file.
Directive Controller
Directives can have their own controllers. This is where you put the logic that is specific to that component, making it a self-contained unit of functionality.
link function for DOM manipulation and the controller for business logic or exposing an API to other directives.
Summary
AngularJS Directives are the primary tool for building modern, interactive web applications. Built-in directives handle the heavy lifting of data binding and DOM control, while custom directives allow you to create your own reusable UI library. Mastering directives is the key to writing clean, maintainable, and modular AngularJS code.