- 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 API
The AngularJS API is a collection of global JavaScript functions and built-in services that reside within the angular object. These APIs allow developers to perform essential tasks like iterating through collections, comparing data, and, most importantly, bootstrapping your application. Think of the API as the "toolbox" that gives you the necessary hooks to manage data flow, handle browser history, and communicate with external servers without writing repetitive boilerplate code.
angular.isString or angular.isDefined), which are incredibly handy for data validation before processing logic.
Key Components of the AngularJS API
1. Module API
The angular.module function is the starting point of every AngularJS application. It acts as a container for the different parts of your app—controllers, services, and filters. By grouping logic into modules, your code becomes more modular, testable, and readable.
angular.module('myApp', []) creates a new module, while angular.module('myApp') retrieves an existing one.
Example:
// Creating a module with no dependencies
var app = angular.module('userManagementApp', []);
2. Controller API
The angular.controller API is where you define the "brains" behind your view. Its primary job is to set up the initial state of the $scope object and add behavior to it. Controllers should remain "thin," meaning they should only handle the logic needed for the specific UI they control.
Example:
app.controller('ProfileController', function($scope) {
$scope.user = { name: 'Jane Doe', role: 'Admin' };
$scope.updateStatus = function() {
$scope.user.status = 'Online';
};
});
3. Service API
Services are functions or objects that are instantiated once per application (Singletons). They are ideal for sharing data or logic that needs to persist across the entire lifecycle of the app, such as user authentication state.
Example:
app.service('AuthService', function() {
this.isLoggedIn = false;
this.login = function() {
this.isLoggedIn = true;
};
});
4. Factory API
While similar to Services, a Factory is a function that returns an object. It is often preferred because it offers more flexibility in how the object is created and returned. You can perform some internal logic before handing the object back to the caller.
Example:
app.factory('CalculatorFactory', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
};
return factory;
});
5. Directive API
Directives are markers on DOM elements (like attributes or tags) that tell AngularJS to attach a specific behavior or transform the DOM. They allow you to create reusable "widgets" like custom sliders, navigation bars, or data tables.
Example:
app.directive('userGreeting', function() {
return {
restrict: 'E',
template: '<p>Welcome back, User!</p>'
};
});
6. Filter API
Filters are used to transform data before it reaches the user's screen. They don't change the underlying data in your controller; they only change how it is formatted in the HTML template.
Example:
app.filter('reverse', function() {
return function(input) {
return input.split('').reverse().join('');
};
});
7. $http API
$http is a core service that facilitates communication with remote HTTP servers. It wraps the browser's XMLHttpRequest object and returns a "promise," making it easy to handle asynchronous data fetching.
.catch() block in your $http calls to handle network errors or server failures gracefully.
Example:
app.controller('ProductCtrl', function($scope, $http) {
$http.get('/api/products')
.then(function(response) {
$scope.products = response.data;
})
.catch(function(error) {
console.error('Failed to fetch products', error);
});
});
8. $routeProvider API
AngularJS uses the $routeProvider (part of the ngRoute module) to handle navigation. Instead of loading an entirely new page from the server, it swaps out a small section of the page (the ng-view) based on the URL path.
Example:
app.config(function($routeProvider) {
$routeProvider
.when('/dashboard', {
templateUrl: 'views/dashboard.html',
controller: 'DashboardCtrl'
})
.otherwise({ redirectTo: '/dashboard' });
});
9. $scope API
The $scope is an object that refers to the application model. It is the execution context for expressions. Scopes are arranged in a hierarchical structure which mimics the DOM structure of the application.
$rootScope. While it's tempting to put data there so it's accessible everywhere, it makes debugging very difficult as your app grows.
10. $compile API
The $compile service is an advanced tool that traverses the DOM looking for directives and attributes. It matches these directives against registered logic and "links" them to a scope. You typically only use this when creating highly complex dynamic components.
Example:
var linkFn = $compile('<div ng-bind="name"></div>');
var element = linkFn($scope);
11. $location API
The $location service parses the URL in the browser address bar and makes it available to your application. Any changes you make to $location are reflected in the address bar, and vice versa. It is much more powerful than window.location because it integrates with the AngularJS lifecycle.
Example:
app.controller('NavCtrl', function($scope, $location) {
if ($location.path() === '/admin') {
$scope.isAdminView = true;
}
});
12. $timeout API
The $timeout service is the AngularJS version of window.setTimeout. The critical difference is that $timeout automatically triggers a "Digest Cycle" (the process where Angular checks for data changes). If you use the standard JavaScript setTimeout, your UI might not update when your data changes.
Example:
app.controller('AlertCtrl', function($scope, $timeout) {
$scope.showAlert = true;
// Hide the alert automatically after 3 seconds
$timeout(function() {
$scope.showAlert = false;
}, 3000);
});
Summary
The AngularJS API provides a comprehensive framework for building robust Single Page Applications. By mastering these core services and functions, you move away from manual DOM manipulation and toward a declarative way of building software. Whether you are managing complex state with Services, transforming data with Filters, or handling navigation with $routeProvider, the API ensures your application remains organized and maintainable. As you build more complex apps, remember to favor modularity and lean on built-in services like $http and $timeout to keep your code in sync with the AngularJS digest cycle.