Friday, 22 April 2016

services in angular

Service:

Services is a singleton object. It will create instance only for the first time, after that it will reuse that object.

syntax:
angular.module("module_name").service("service_name", function(){
//constroctor function
})

Example:
angular.module('myApp.service',[]).service("helloService", function(){
this.name = "saritha",
this.company = "cts"
this.display = function(){
alert(this.name);
}
});

Inject this service module into another module to reuse.

var myApp = angular.module('myApp',['myApp.controller','myApp.service']);


In controller we can use it as:

angular.module('myApp.controller',[]).controller('demoController1',['$scope', 'helloService',function($scope, helloService){
helloService.display();
}]);

output: output the alert

advantages:
Easy to create object,
Less time to execute,
Reusabuluity

drawbacks:
It is very difficult to execute for larger code.

No comments:

Post a Comment