Search within TutorialsPark

AngularJS Modules and Services


Learn how to oraganise the modules and services within an AngularJS Application


AngularJS Services and Modules

AngularJS services have functionality which can be reused in an application, it is a functionality which is affected by multiple components within the application. The most common uses of services are for networking, security, user login/logout.

In terms of Model Control View, services do not belong to either the model controller or view.

In any AngularJS application Modules have two purposes, first is to define functionality of the application which is applied using directive ng-app, and second is to create reusable functionality like services, directives and filters.

In short, services are reusable functionality which can be used across applications, and modules are used to package these functionalities so that it can be used across multiple applications.


AngularJS Services and Modules : Using Modules to create an Application

Almost all AngularJS examples until now were single page comprising of scripts and HTML code, but real applications are large a single page would be hard to manage and maintain.

Hence, we use the script element to organise seperate files and reference them from the main HTML file.The organisation of these modules depends upon the requirement of the project.


AngularJS Services and Modules : Using a Single Module

The most simple way to organise components within an Application is to include them within the same module.In the example we have moved the directive from the main page into a new file called demoDirective.js

In the file demoDirective.js we call the method angular.module to pass in the name of the module defined in the main example.

Table : Validation method and properties provided by the Ng Model Controller

Name Description
animation(name, factory) To set the animation feature
config(callback) To register a function that can be used to configure a module.
constant(key, value) To create a service that returns a constant value.
controller(name, constructor) To define a controller.
directive(name, factory) To define a directive.
factory(name, provider) To define a service, using the factory method.
filter(name, factory) To define a filter inorder to format the data to be displayed to the user.
provider(name, type) To define a service, using the provider method.
name To return the name of the module.
run(callback) To register a function that is invoked when AngularJS has done loading and configuring all the modules.
service(name, constructor) To define a service, using the service method.
value(name, value) To define a service which returns a constant value.

Example: AngularJS Service Modules demoDirective.js File

Example: AngularJS Service Modules Using a Single Module

Give it a TRY! » Note:The HTML block comprises of element ol and li, with the directive ng-repeat