Services

A service is a function or object that is available for an AngularJS application.  You can use any of the built-in services or create your own service. Notice that all services start with a dollar sign ($).

$location service

The $location service returns information about the current web page location by passing it into a controller as an argument. It must be defined as a dependency.

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $location) {
$scope.myUrl = $location.absUrl();
});
</script> <div ng-app="myApp" ng-controller="myCtrl">
<p>This page absoulte URL is: <strong>{{myUrl}}</strong></p>
</div>
Services: $location Service Demo

NOTE: AngularJS constantly supervises the application.  Because of this, it is best to have AngularJS use the $location service instead of the window.location object.

$http Service

The $http service makes a server request for data and lets an application handle the response. In the example below, the $http service make a server request for a page using the get method and then set the value to the myMesssage variable as a response:

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.html").then(function (response) {
$scope.myMessage = response.data;
});
});
</script> <div ng-app="myApp" ng-controller="myCtrl">
<h1>Response from server:</h1> {{myMessage}}
</div>
Services: $http Service Demo

The welcome.html page on the server is:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome Page</title>
</head> <body>
<h1>Hello from the server.</h1>
</body>
</html>
There are several METHODS that can be used with an $http service:

The example below executes the $http service with an object as an argument. The object is specifying the HTTP method, the url, what to do on success, and what to do on failure:

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http){
$http({
method : "GET",
url : "welcome.html"
}).then(function mySuccess(response){
$scope.myMessage = response.data;
}, function myError(response){
$scope.myMessage = response.statusText;
});
});
</script> <div ng-app="myApp" ng-controller="myCtrl">
<p><strong>Message from server:</strong></p> {{myMessage}}
</div>
Services: $http Service Demo 2 (ERROR MESSAGE IS NOT WORKING)

The response from the server is an object with these PROPERTIES:

Below is an example that uses several $http service properties:

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http){
$http.get("welcome.html")
.then(function(response){
// Function that will be executed if the file load successfully
$scope.content = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statusText;     
}, function(response){
// Function that will be executed if there is a failure
$scope.content="Error loading file!"});
});
</script> <div ng-app="myApp" ng-controller="myCtrl">
<p>Data: <strong>{{content}}</strong></p>
<p>Status: <strong>{{statuscode}}</strong></p>
<p>StatusText: <strong>{{statusText}}</strong></p>
</div>
Services: $http Service Demo 3 

NOTE: If you change the file name welcome.html to a bogus file, you will see the error message.

$timeout Service

The $timeout service is similar to the window.setTimeout function. In the example below, a new message is displayed every 15 seconds. The $timeout service will run a function after a specified number of milliseconds.

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout){
$scope.myHeader = "Hello, World!";
$timeout(function (){
$scope.myHeader = "Goodbye, World!";
}, 2000);
});
</script>

<div ng-app="myApp" ng-controller="myCtrl">
<p>This message will change in five seconds: {{myHeader}}</p>
</div>
Services: $timeout Service Demo

$interval Service

The $interval service is similar to the window.setInterval function. The $interval service runs a function every specified millisecond. In the example of the clock below, every second:

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval){
$interval(function (){
$scope.currentTime = new Date().toLocaleTimeString();
}, 1000);
});
</script> <div ng-app="myApp" ng-controller="myCtrl">
<h1>{{currentTime}}</h1> </div>

Services: $interval Service Demo

BONUS: Style Clock with CSS

Download the following digital font:into the same folder:

digital-7 (mono)

Add the following CSS style ABOVE the closing head tag (</head>).

<style>
@font-face
{
font-family:digital;
src:url("digital-7 (mono).ttf");
}

#clock {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
color: #17D4FE;
font-size: 150px;
font-family:digital;
background-color: black;
letter-spacing: 7px;
width:900px;
text-align: center;
border: 5px solid #17D4FE;
border-radius: 30px;
-webkit-box-shadow: 6px 10px 15px #070000;
box-shadow: 6px 10px 15px #070000;
}
</style>

Add the following highlighted id to the h1 element.

<div ng-app="myApp" ng-controller="myCtrl"> 
<h1 id="clock">{{currentTime}}</h1>
</div>

CHECK POINT:
Save the file and preview it in a browser. You should see that it has been "styled" with the CSS attributes.



Create Custom Service

You can create your own service by connecting it to a module. Once you create a service and connected it to an application, you can use it in any controller, directive, filter, or even inside other services. In the example below,  a service is used inside of a filter by adding a dependency to create a hex converter that will convert a number into a hexadecimal value:

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, hexafy){
$scope.hex = hexafy.myFunc(255);
});
app.service('hexafy', function(){
this.myFunc = function (x){
return x.toString(16);
}
});
</script> <div ng-app="myApp" ng-controller="myCtrl">
<p>The hexadecimal value of 255 is: <strong>{{hex}}</strong></p>
</div>
Services: $Custom Service Demo

In this example, this filter uses a service that converts numbers into hexadecimal values.
MAKE IT WORK CORRECTLY WITH RGB VALUES

<script>
var app = angular.module('myApp', []);
app.service('hexafy', function(){
this.myFunc = function (x){
return x.toString(16);
}
});
app.filter('myFormat',['hexafy', function(hexafy){
return function(x) {
return hexafy.myFunc(x);
};
}]);
app.controller('myCtrl', function($scope){
$scope.rgb = [255, 251, 200];
});
</script> <div ng-app="myApp" ng-controller="myCtrl">
<p>Filtered array [255, 251, 200]:</p>
<p ng-repeat="x in rgb" style="display:inline"> {{x | myFormat}}</p>
</div>
Services: $Custom Service Demo 2

The response is a JSON format, so it may sense to provide JSON as the data source since it is a great format for any JavaScript project.  First, let’s create a JSON object on the server called family.php:

NOTE: This php file doesn't need to be in the htdocs folder on a PHP server because it does not have any PHP script that need to be processed.

{ "family_member" : [
{"Name": "Cornelius Chopin", "City": "Round Rock", "Gender": "Male"},
{"Name": "Sheila Chopin", "City": "Round Rock", "Gender": "Female"},
{"Name": "Joshua Chopin", "City": "Round Rock", "Gender": "Male"},
{"Name": "Josiah Chopin", "City": "Round Rock", "Gender": "Male"}
]
}

Then, write the HTML with some AngularJS code:

<script>
var app = angular.module('myApp', []);
app.controller('familyCtrl', function($scope, $http){
$http.get("family.php").then(function (response){
$scope.myFamily = response.data.family_member;
});
});
</script> <ul ng-app="myApp" ng-controller="familyCtrl">
<li ng-repeat="x in myFamily">{{x.Name + ', ' + x.City + ', ' + x.Gender}}</li>
</ul>
Services: Service with JSON Demo

NOTES: