AngularJS — Directives
Built-in Directives
| Directive | Description |
|---|---|
| ng-app | Root element |
| ng-controller | Controller |
| ng-model | Two-way binding |
| ng-repeat | Loop through items |
| ng-show/ng-hide | Show/hide elements |
| ng-if | Add/remove from DOM |
| ng-click | Click handler |
| ng-class | Add/remove classes |
| ng-style | Inline styles |
ng-repeat
<ul>
<li ng-repeat="item in items">{{item.name}}</li>
</ul>
<!-- With index -->
<li ng-repeat="item in items track by $index">
{{$index + 1}}. {{item.name}}
</li>
ng-show and ng-hide
<div ng-show="isVisible">Visible when true</div>
<div ng-hide="isVisible">Hidden when true</div>
ng-if
<div ng-if="isLoggedIn">Welcome back!</div>
<div ng-if="!isLoggedIn">Please log in</div>
ng-class
<div ng-class="{active: isActive, highlight: isHighlighted}">
Content
</div>
ng-click
<button ng-click="count = count + 1">Click me</button>
<p>Count: {{count}}</p>
Custom Directive
app.directive('myDirective', function() {
return {
restrict: 'E',
template: '<div>{{text}}</div>',
scope: {
text: '@'
}
};
});
Mini Practice
- Use ng-repeat
- Show/hide elements
- Apply conditional classes
- Create a custom directive
Up Next
Continue with Events — AngularJS events.
Related Topics
Frequently Asked Questions about Directives
What is Directives in AngularJS?
Directives is a fundamental concept in AngularJS. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Directives?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Directives.
Why is Directives important in AngularJS?
Directives is essential for AngularJS development. Understanding this concept will help you write better code and solve real-world problems more effectively.