Services

Services give you a simple way to reuse complex logic. You can either use the predefined services provided by the AngularJS-framework or define your own. Predefined services all begin with $, so avoid to begin your customs services with this character.

Services are singletons and instantiated the first time you use them in your project. Singleton is a softwaredevelopment-pattern which makes sure that an instance of an object exists only once.

Lets begin with a simple example of a service.

The $interval service

If you need to execute code in a specific timeinterval, you can use the $interval service, which allows you to define

  • Which function
  • in which intervall
  • how many times

has to be executed. In our following example we’ll use it to increment a number in a text-input after 750 milliseconds. As you can see the $interval-service can be called like a simple method-call, which makes them very easy to use.

Example

<div ng-app="" ng-controller="counterController">
	Counter: <input type="text" ng-model="counter">
</div>

<script>
	function counterController($scope, $interval) {
		$scope.counter = 0;
		$scope.incrementCounter = function() {
			$scope.counter  += 1;
	}

	$interval($scope.incrementCounter, 750, 5);
}
</script>

Play with example »

The $http service

So far we have used only local data. For real applications you will need to load data from web- or rest-services which your server exposes. If you need some free accessible json-data to play around, you can use i.e. yql (Yahoo Query Language), which provides several kinds of data. The most simple way is to use the yql-console, which lets you create queries and provides an url for this query. Another site providing plenty of json-data is data.gov, which you could use as well. For our next example we’ll load google-books via the yql  and display them in a list with the ng-repeater directive.

If you want to preview the example, click on the button below:
Play with example »

Downloading the data
First look at the bookController. The yahooQueryUrl defines a query to load the first three c# books from the google-books. With the $http.get-method call the json-result will be downloaded. When the download is finished, the then-method is called, which passes the result to $scope.bookList. This was the simple explanation of how the $http-service works. After the example we’ll go more into detail to cover promises, which are returned by the $http.get-method.

<script>
function bookController($scope, $http){
	var yahooQueryUrl =
		"https://query.yahooapis.com/v1/public/yql?q=" +
		"SELECT%20*%20FROM%20google.books%20" +
		"WHERE%20q%3D%22c%23%22%20AND%20maxResults%3D3&" +
		"format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";

	$http.get(yahooQueryUrl).then(function(bookList) {
		$scope.bookList = bookList.data.query.results.json;
	});
}
</script>

Displaying the data

Now all data is in $scope.bookList and we can iterate over the items in it. New in this example is the AngularJS-directive ng-src, which is used to display the image in the url of book.volumeInfo.imageLinks.smallThumbnail.

<div ng-controller="bookController">
	<table>
		<tr ng-repeat="book in bookList.items">
			<td><img ng-src="{{ book.volumeInfo.imageLinks.smallThumbnail }}"/></td>
			<td>{{ book.volumeInfo.title }}</td>
			<td>{{ book.volumeInfo.publisher }}</td>
		</tr>
	</table>
</div>

Most interesting AngularJS services

As you can see, services are easy to use and do not need any complex setup. AngularJS provides you more services. You will not really need all of them in the beginning, so I’ll tell you here something about the most interesting.

ServiceDescription
$anchorScrollLocates an html-element and then scroll to it.
$animateManipulates the DOM. You can do things suchs as inserting and removing elements or adding and removing css-classes.
$documentProvides access to the window.document-object, which provides i.e. the site-title.
$filterFormats strings. You can i.e. change a string to upper- or lowercase
$httpCommunicates with remote-http servers. Allows i.e. to call web- or restservices.
$intervalCalls repeatedly a function after n milliseconds.
$timeoutCalls a function, when a certain time elapsed.
$windowProvides access to the window-object. To make testing possible, you should always use the $window-variable in AngularJS