The Service in AngularJS
AngularJS supports the concepts of "Seperation of Concerns" using the service structure. Service is JavaScript functions and is responsible for certain tasks. It makes them separate entities that are easy to maintain and test. Controller, filter can call them simply. Service is often injected using AngularJS's dependency injection mechanism.
AngularJS provides a lot of predefined services: $ http, $ scope, $ route, $ window, $ location . Each service has certain tasks. For example, $ http is used to create ajax requests on the server to retrieve data. $ route is used to define routing information . The default AngularJS service starts with the $ symbol.
There are two ways to create a service:
- factory
- service
Use factory method in AngularJS
When using the factory method, we first define the factory and attach the method to it.
var ungdungAngularJS = angular . module ( "ungdungAngularJS" , []); ungdungAngularJS . factory ( 'toanhocService' , function () { var factory = {}; factory . phepnhan = function ( a , b ) { return a * b } return factory ; });
Use service method in AngularJS
Using the service method, we will define the service then assign the method to it. We also inject the services available to it.
ungdungAngularJS . service ( 'tinhBPService' , function ( toanhocService ) { this . binhphuong = function ( a ) { return toanhocService . phepnhan ( a , a ); } });
For example:
Below is an example to illustrate the above instruction.
testAngularJS.jsp
Vi du Service in AngularJS
You should read it
- What is AngularJS?
- Ajax in AngularJS
- Instructions for installing AngularJS
- The Module in AngularJS
- View components in AngularJS
- The Filter in AngularJS
- Directive in AngularJS
- Form in AngularJS
- Create the first AngularJS application
- Multilingual (i18n) in AngularJS
- HTML DOM element in AngularJS
- Expression in AngularJS
Maybe you are interested
Google Essentials Launches: An Easy Solution to Access Google Services on Windows
AWS will discontinue Cloud9, CodeCommit, CloudSearch, and several other services
Google launches a calling support service on many different devices
Top of the best free email services
Google increases the reward by 5 times for hackers who discover security errors in its services
What are DoS and DDoS denial of service attacks? What are their harmful effects?