Skip to content

Instantly share code, notes, and snippets.

@hemantajax
Last active August 29, 2015 14:00
Show Gist options
  • Save hemantajax/563707b7b45d2942abcf to your computer and use it in GitHub Desktop.
Save hemantajax/563707b7b45d2942abcf to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>REST API calls with Angular ngResource module</title>
<link href="http://getbootstrap.com/dist/css/bootstrap.css" rel="stylesheet" type="text/css" />
<style>
[ng\:cloak],
[ng-cloak],
[data-ng-cloak],
[x-ng-cloak],
.ng-cloak,
.x-ng-cloak {
display: none !important;
}
</style>
</head>
<body ng-app="restApp" ng-cloak>
<div class="container" ng-controller="BooksCtrl">
<h1>All Books</h1>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="book in books">
<td>{{ book.id }}</td>
<td>{{ book.name }}</td>
<td>{{ book.isbn }}</td>
<td>{{ book.createdOn }}</td>
</tr>
</tbody>
</table>
</div>
<script src="https://code.angularjs.org/1.2.16/angular.min.js"></script>
<script src="https://code.angularjs.org/1.2.16/angular-resource.min.js"></script>
<script>
var restApp = angular.module("restApp", ["ngResource"]);
restApp.factory("BookService", function($resource) {
return $resource('http://hkapi.herokuapp.com/books/:id', {}, {update: { method: 'PUT' }});
});
restApp.controller("BooksCtrl", function($scope, BookService) {
// 1 : Fetch all Books
// GET /books
$scope.books = BookService.query(function(data) {
console.log("Got all books", data);
});
// 2: Fetch single book
// GET /books/729e31b4736718b8
BookService.get({
id: "729e31b4736718b8"
}, function(data) {
console.log("got single Record", data);
});
// 3: Create a new book
// POST /books
BookService.save({
name: "Javascript 1",
isbn: "asdas326523424324"
}, function(data) {
$scope.books.push(data);
console.log("success ", data);
}, function(data) {
console.log(data);
});
// 4: Delete a book
// DELETE /books/9971d98ce85d6972
BookService.remove({
id: "9971d98ce85d6972"
}, function(data) {
console.log("Book Removed");
});
// 5: Update a book
// POST /books/9779f7580d6fc808
BookService.update({
id: "9779f7580d6fc808",
name: "JS Awesome Book Part 3",
isbn: "55555"
}, function(data) {
console.log("update success ", data);
}, function(data) {
console.log(data);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment