1. Introduction to AngularJS
Overview of AngularJS:
AngularJS is a JavaScript-based open-source front-end web framework developed by Google. It was initially released in 2010 and is primarily used for building dynamic, single-page applications (SPAs). AngularJS simplifies both the development and the testing of such applications by providing a framework for client-side model–view–controller (MVC) architecture, along with components commonly used in rich internet applications (RIA).
Some of the features that make AngularJS popular include:
- Two-way data binding: Synchronizes data between the model and the view.
- Dependency Injection: Facilitates easier testing and development.
- Directives: Allows developers to extend HTML with custom attributes and elements.
- Routing: Helps in managing navigation and views in single-page applications.
AngularJS differs from Angular (2+), which is a complete rewrite of the original AngularJS and not backward-compatible.
Key Features:
- MVC Architecture: AngularJS follows the Model-View-Controller architecture.
- Directives: These are special attributes in HTML used to extend the behavior of elements.
- Data Binding: Two-way binding allows automatic synchronization of data between the model and the view.
- Dependency Injection: AngularJS has a built-in dependency injection subsystem that allows easy management of service instances.
- Routing: AngularJS has a powerful routing mechanism that helps manage navigation between different views in a single-page application.
- Templating: AngularJS provides a templating engine that allows you to create dynamic views using HTML and AngularJS expressions.
Basic Setup and Installation:
To get started with AngularJS, you need to include the AngularJS library in your project. The easiest way to do this is by adding the following script tag to your HTML file:
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Application</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-app="">
<h1>{{ message }}</h1>
</div>
<script>
function MyController($scope) {
$scope.message = "Hello, AngularJS!";
}
</script>
</body>
</html>
MVC Architecture in AngularJS:
AngularJS implements MVC architecture, which is broken down into three components:
- Model: The data of the application.
- View: The user interface (UI) of the application, built using HTML.
- Controller: JavaScript functions that handle the logic for the application, connecting the model and the view.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
2. AngularJS Directives
Directives in AngularJS are special markers on the DOM element (such as attributes, element names, comments, or CSS classes) that tell AngularJS to do something to that DOM element (like attaching a behavior to it or transforming the DOM element).
Built-in Directives:
- ng-app:
The ng-app directive initializes an AngularJS application. It defines the root element for the AngularJS application and is typically used at the <html> or <body> tag.
<div ng-app="myApp">
<!-- AngularJS code will be active here -->
</div>
- ng-model:
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
<input type="text" ng-model="name">
<p>{{ name }}</p>
- ng-bind:
The ng-bind directive binds the value of an expression to the content of an HTML element.
<p ng-bind="name"></p>
- ng-repeat:
The ng-repeat directive repeats a set of HTML elements once for each item in a collection.
<ul>
<li ng-repeat="person in people">{{ person.name }}</li>
</ul>
Custom Directives:
In addition to the built-in directives, AngularJS allows developers to create their own custom directives. A directive can be defined using the directive function.
app.directive("customDirective", function() {
return {
template: "<h1>This is a custom directive!</h1>"
};
});
In the HTML, the custom directive can be used like this:
<custom-directive></custom-directive>
Custom directives can also have isolated scopes, allowing them to encapsulate behavior and data.
3. AngularJS Expressions
AngularJS expressions are used to bind data to HTML. They work much like JavaScript expressions but have the following differences:
- They do not use loops or conditionals.
- They are executed in the context of the scope object.
Data Binding
AngularJS expressions are often used in double curly braces {{ expression }} to bind data to the view.
<p>The sum of 1 and 1 is {{ 1 + 1 }}</p>
Expressions vs. JavaScript
- No access to global objects: AngularJS expressions cannot access JavaScript global variables such as window, document, or Math.
- Safe evaluation: If the expression tries to perform any unsafe actions, AngularJS will stop evaluating and throw an error.
<p>{{ x * y }}</p>
4. Controllers in AngularJS
Definition
Controllers in AngularJS are used to build the logic of the application. They are JavaScript functions that are bound to a specific scope. Controllers are defined using the controller method in a module.
app.controller('myCtrl', function($scope) {
$scope.name = "AngularJS";
});
Role of Controllers
Controllers are responsible for:
- Initializing application data.
- Handling events.
- Communicating with the services to fetch or send data.
Using $scope Object
The $scope object is an essential part of AngularJS controllers. It allows you to bind variables and functions between the controller and the view.
app.controller('myCtrl', function($scope) {
$scope.message = "Hello World!";
});
In the HTML file:
<div ng-controller="myCtrl">
<p>{{ message }}</p>
</div>
5. Filters in AngularJS
Built-in Filters:
Filters in AngularJS allow you to format data displayed to the user. Filters can be applied using the pipe (|) symbol.
Common Built-in Filters
- Currency: Formats a number as currency.
{{ amount | currency }}
- Uppercase: Converts a string to uppercase.
{{ name | uppercase }}
- Lowercase: Converts a string to lowercase.
{{ name | lowercase }}
- Date: Formats a date string.
{{ date | date:'fullDate' }}
- LimitTo: Limits an array or string to a specified number of elements/characters.
{{ text | limitTo:10 }}
- OrderBy: Orders an array by a specified property.
<li ng-repeat="item in items | orderBy:'name'">{{ item.name }}</li>
Custom Filters
Custom filters can be created by registering a filter factory function in a module.
In Java script
app.filter('reverse', function() {
return function(input) {
return input.split('').reverse().join('');
};
});
In the HTML:
html
Copy code
<p>{{ 'hello' | reverse }}</p>
-
Services in AngularJS
Built-in Services
AngularJS comes with several built-in services such as $http, $location, $timeout, $interval, and $window. These services can be injected into controllers, filters, or other services.
Custom Services
Custom services can be created in AngularJS by using the service or factory methods.
javascript
Copy code
app.service('myService', function() {
this.sayHello = function() {
return "Hello from service!";
};
});
Using the service in a controller:
Copy code
app.controller('myCtrl', function($scope, myService) {
$scope.message = myService.sayHello();
});
Dependency Injection
AngularJS uses dependency injection (DI) to inject services, factories, and other dependencies into controllers or services. This ensures that your code is modular, testable, and easy to maintain.
javascript
Copy code
app.controller('myCtrl', function($scope, $http) {
$http.get('data.json').then(function(response) {
$scope.data = response.data;
});
})
-
Routing and Views
Setting Up Routes
AngularJS allows you to define routes to different views in your single-page application using the $routeProvider service.
javascript
Copy code
app.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
redirectTo: '/home'
});
});
Using $routeProvider
The $routeProvider is used to configure routes in AngularJS. Each route specifies a template and a controller.
Nested Views
AngularJS supports nested views using directives like ng-view. Nested views can help you manage complex application layouts.
html
Copy code
<div ng-view></div>
-
Forms in AngularJS
Form Validation
AngularJS provides built-in validation for forms. It includes validation for required fields, email, number, URL, and custom validation logic.
html
Copy code
<form name="myForm">
<input type="email" name="userEmail" ng-model="user.email" required>
<span ng-show="myForm.userEmail.$error.required">Email is required.</span>
</form>
Input Types
AngularJS supports several input types such as text, email, number, date, and more.
Handling Form Submissions
Forms in AngularJS are typically handled by submitting the form data to a controller function. This can be done by attaching the ng-submit directive to the form.
html
Copy code
<form ng-submit="submitForm()">
<input type="text" ng-model="name">
<button type="submit">Submit</button>
</form>
-
Modules in AngularJS
Creating and Using Modules
Modules are containers for different parts of an AngularJS application such as controllers, services, filters, and directives. Modules are created using the angular.module() method.
javascript
Copy code
var app = angular.module('myApp', []);
Injecting Dependencies
You can inject dependencies into your modules to provide additional functionality. For example, if you want to use routing in your application, you can inject the ngRoute module.
javascript
Copy code
var app = angular.module('myApp', ['ngRoute']);
Module Methods
Modules in AngularJS have several methods like controller(), service(), factory(), directive(), config(), and run(), which allow you to define various components and configurations.
-
HTTP Communication
Using $http for AJAX Calls
The $http service is used to communicate with a remote server via the browser’s XMLHttpRequest object or via JSONP.
javascript
Copy code
app.controller('myCtrl', function($scope, $http) {
$http.get('https://api.example.com/data')
.then(function(response) {
$scope.data = response.data;
});
});
$http Methods
The $http service has several methods:
- $http.get(): Used to make a GET request.
- $http.post(): Used to make a POST request.
- $http.put(): Used to make a PUT request.
- $http.delete(): Used to make a DELETE request.
Error Handling
You can handle errors in $http requests by chaining the .catch() method to handle failed requests.
javascript
Copy code
$http.get('https://api.example.com/data')
.then(function(response) {
$scope.data = response.data;
})
.catch(function(error) {
console.log('Error occurred:', error);
});
-
AngularJS Events
Event Handling
AngularJS allows you to handle DOM events like clicks, keypresses, and changes using the ng-click, ng-keypress, and ng-change directives.
html
Copy code
<button ng-click="handleClick()">Click me</button>
Using $scope.$on, $scope.$emit, and $scope.$broadcast
AngularJS provides a way to handle custom events with the $scope.$on, $scope.$emit, and $scope.$broadcast methods. These methods allow communication between different parts of your application.
- $scope.$on(): Listens for a specific event.
- $scope.$emit(): Emits an event upwards in the scope hierarchy.
- $scope.$broadcast(): Broadcasts an event downwards to all child scopes.
javascript
Copy code
scope.$on('customEvent', function(event, args) {
console.log('Event received:', args);
});
$scope.$emit('customEvent', { message: 'Hello' });
-
Two-way Data Binding
Explanation of Two-way Data Binding
Two-way data binding is one of AngularJS’s core features. It allows changes in the model to reflect automatically in the view, and vice versa.
html
Copy code
<input type="text" ng-model="name">
<p>{{ name }}</p>
Binding with ng-model
The ng-model directive is used to create a two-way binding between the model and the view.
html
Copy code
<input type="text" ng-model="username">
-
Custom Directives
Creating Custom Directives
Custom directives are one of the most powerful features of AngularJS, allowing you to create reusable components.
javascript
Copy code
app.directive('myDirective', function() {
return {
restrict: 'E',
template: '<h1>Custom Directive</h1>'
};
});
Isolating Scope
In some cases, you may want to isolate the scope of a directive to avoid interfering with the parent scope.
javascript
Copy code
app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
message: '@'
},
template: '<p>{{ message }}</p>'
};
});
-
AngularJS Animation
Animating with ngAnimate
AngularJS has an ngAnimate module that enables animations when certain directives are used (e.g., ng-show, ng-hide, ng-repeat).
To use animations, you need to include the ngAnimate module in your application:
javascript
Copy code
var app = angular.module('myApp', ['ngAnimate']);
CSS and JavaScript-based Animations
You can create animations using CSS or JavaScript. For CSS animations, AngularJS adds and removes CSS classes during the different phases of the animation.
css
Copy code
.fade-in {
transition: opacity 0.5s ease-in-out;
opacity: 0;
}
.fade-in.ng-enter {
opacity: 1;
}
-
Testing in AngularJS
Unit Testing with Karma and Jasmine
AngularJS applications can be tested using the Karma test runner and the Jasmine testing framework. You can write unit tests for your controllers, services, and directives.
Here’s a simple unit test for a controller:
javascript
Copy code
describe('MyController', function() {
beforeEach(module('myApp'));
var $controller;
beforeEach(inject(function(_$controller_) {
$controller = _$controller_;
}));
it('should initialize the name variable', function() {
var $scope = {};
var controller = $controller('myCtrl', { $scope: $scope });
expect($scope.name).toEqual('AngularJS');
});
});
End-to-End Testing with Protractor
For end-to-end testing, AngularJS uses Protractor, a testing framework built on top of WebDriverJS that automates browser interactions for testing user interfaces.
javascript
Copy code
describe('My AngularJS App', function() {
it('should have a title', function() {
browser.get('index.html');
expect(browser.getTitle()).toEqual('My AngularJS App');
});
});
This AngularJS provides a comprehensive guide to the framework, covering key concepts and functionalities. It helps both beginners and advanced developers with essential topics such as directives, controllers, routing, services, and testing in AngularJS.