Introduction to methods of using factory and service in Angularjs
AngularJS supports the concept of "separation of concerns" with the architecture of the service. The service is a JavaScript function and is responsible for doing only a specific task. This also makes them a separate entity for maintenance and testing. controllers, filters can invoke them as a basis for demand. The service is injected normally using AngularJS's dependency injection mechanism.
AngularJS provides many internal services such as:$http, $route, $window, $location , etc. Each service is responsible for, for example, a specific task,$http is used to create AJAX calls to obtain the server's data. $route used to define routing information, and so on. The built-in service always prefixes the $ sign.
There are two ways to create a service.
Factory
Service
Using factory methods
For a service that already has an instance object, Factory takes precedence and returns the object directly. For example , to share passing data between multiple controllers , and to encapsulate $resource request resources.
Using the factory method, we first define a factory and then assign the method to it.
var Mainapp = angular.module ("Mainapp", []); Mainapp.factory (' MathService ', function () { var factory = {}; Factory.multiply = function (A, b) { return a * b } return factory;
Using service methods
For services that require new creation, the service takes precedence,and Angular automatically new and creates the object instance. The service makes it easier to organize an API of the same set of business logic , making the business logic more cohesive.
Using the service approach, we define a service and then assign the method. It also injects services that are already available.
Mainapp.service (' Calcservice ', function (mathservice) { this.square = function (a) { return Mathservice.multiply (a,a); }});
Example
The following example shows all of the above instructions.
Testangularjs.html
ResultsOpen textangularjs.htmlin your Web browser. See the results as follows :
American and American PicturesAngularjs Advanced (33) A brief introduction to the Book of the Sea the method of using factory and service in Angularjs