Angularjs Service Factory

Monday, March 7th, 2016 (0 Comment)

Perhaps you have heard of the concept of Service, such as the PHP Service, its task like an API for returning results to the client. For AngularJs is nothing else, angularjs service is the function performed a particular task.

1. AngularJs service

AngularJs Service has a very important role in applications written in AngularJS, the service is available and was provided by Angularjs, but we absolutely can expand by creating a Service each. Here is a list of Service available in AngularJS:

  • $anchorScroll
  • $animate
  • $cacheFactory
  • $compile
  • $controller
  • $document
  • $exceptionHandler
  • $filter
  • $http
  • $httpBackend
  • $interpolate
  • $interval
  • $locale
  • $location
  • $log
  • $parse
  • $q
  • $rootElement
  • $rootScope
  • $sce
  • $sceDelegate
  • $templateCache
  • $templateRequest
  • $timeout
  • $window

 

You notice the name of the service will begin with the $ symbol, this means that all available service we must have the front $ symbol.

2. How to create a new Service in AngularJs?

There are two ways we define a new service as follows:

  • Use Factory method
  • Use Service method

2.1. Create service by Factory method

Example 1: Write a program that includes an input box, you enter if the value is divisible by 2, the notification appears on-screen is an even number, otherwise notification is odd.

Demo

  • Line 28-39: This service is created with the name code is check number, this service will use $window service available to process information more alert.
  • Line 23: The controller uses this services, it will have to transfer number to the value.

2.2. Create angularjs service by Service method

Example 2: The same example 1, you only change at line 28 is module.factory to module.service

Demo

3. Call service in service

Example 3: the same example 1, but split into two different service, the first service used to check a number is an even number or not, the second service is tasked validate the value and use to test the first service. This is like you create a function validate, in validate the function used the check_number function.

Demo

  • Line 28-39: create the first service, it will call the second service
  • Line 42-48: create the second service.

Tags: , ,

Related Posts

angularjs
Angularjs filter checkbox examples mvc
angularjs
Angularjs listbox examples mvc
angularjs
Angularjs combobox examples mvc
angularjs
Create update delete CRUD in Angularjs MVC

Related Posts

angularjs
Angularjs filter checkbox examples mvc
angularjs
Angularjs listbox examples mvc
angularjs
Angularjs combobox examples mvc
angularjs
Create update delete CRUD in Angularjs MVC

Leave a Reply

Your email address will not be published. Required fields are marked *