AngularJS: Services: Tutorial 6
Dec 24, 2015
2 min read
AngularJs

by adityaswami89
Contributor
Article Series
- Tutorial 1: Angular JS
- Tutorial 2: Controllers
- Tutorial 3: Controllers
- Tutorial 4: Controllers: Advanced
- Tutorial 5: Models
- Tutorial 6: Services
Prerequisites: Angularjs tutorial 5
In today's blog, we will look at how to call a service from your AngularJS application. For the sake of simplicity, instead of creating a REST service, I am utilizing a service from w3schools:
You can as well write your complex service and expose that to be used in your Angular App.
Angular has exposed a library called as $http: The $http
service is a core Angular service that facilitates communication with the remote HTTP servers via the browser’s XMLHttpRequest object or via JSONP.
Methods that are available (source Angular website):
We will be using a simple get
for our demo purpose.
Our JS file would look as below:
var Namespace = angular.module('Namespace', []); Namespace.controller('StoreController', function ($http, $log, $q, $scope) { $scope.name = "Aditya S"; $scope.bookarray = []; $scope.greeting = null; $scope.servicebook = null; $http.get('http://www.w3schools.com/angular/customers.php'). success(function (data) { $scope.greeting = data; }); });
From the above, we are using a $http.get
to retrieve the data from the service which would be available in “data
”. We could then parse this and perform further operations or for simplicity, I have filled in data in greeting
.
Our html page would look as below:
<!DOCTYPE html> <html lang="en" ng-app="Namespace"> <head> <meta charset="utf-8"> <title>Book Cart</title> <link rel="stylesheet" type="text/css" href="css/templates.css" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"> </script> <script src="javascript/app.js"></script> </head> <body ng-model="Namespace" ng-controller="StoreController"> Hello {{name}} <h1>Welcome to my book store</h1> <div style="width: 100%; overflow: scroll;"> <div ng-repeat="data in greeting.records"> The Name is <b>{{data.Name}}</b> The Country is <b>{{data.Country}}</b></div> </div> </body> </html>
I am using ng-repeat
to parse through the results and display it. The output would be as below. Further, we would look how to create a mobile Application using Ionic in our further blogs.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)