Angular Service Basics

Services

Angular services are singletons. They can be used module or application wide. Services are where you should store data that you don't want to lose between screens and different controllers. We are going to cover basic services. There is also a provider service, and a factory service.

They are also great for modularizing your code. You might create a service that performs network/http requests. You might have a service that stores global data for your application, or a service where you can access constants to prevent code duplication.

This syntax can be written as follows:

var app = angular.module('learningAngular');

app.service('dataService', function() {
    this.personLoggedIn = undefined;
});

Services can live the in the same script where its parent module is declared or they can be in other script files. If you put a service in another script file, you have to grab a reference to your module as we did above. This time you don't add any dependencies since you aren't creating the module, but just referencing it.

To use your service in your controller you'll need to include it as a dependency as follows:

var app = angular.module('learningAngular',[]);

app.controller('mainCtrl', function($scope, dataService) {
	$scope.person = {
		firstName: "John",
		lastName: "Smith"
	};
	
	$scope.getFullName = function() {
		return $scope.person.firstName + ' ' + $scope.person.lastName;
	}
	
	dataService.personLoggedIn = $scope.person;
});