AngularJS - Book Service ex.
http://stackoverflow.com/questions/11850025/recommended-way-of-getting-data-from-the-server
by gavinfoley
HTML
<div data-ng-app="myApp">
<div data-ng-controller="MyCtrl"></div>
</div>
CSS
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.1.6/css/foundation.min.css"> <link rel="stylesheet" href="//rawgit.com/minipai/ng-trans.css/master/ng-trans.min.css"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-animate.min.js"></script> <style>
JavaScript
//Include angular-ui dependency in resources on the side and as 'ui'
angular.module('myApp', ['ngAnimate'])
.controller("MyCtrl", function ($scope, $timeout, Book) {
// to retrieve a book
var bookPromise = Book.get(123);
bookPromise.then(function (b) {
book = b;
console.log(book);
});
var newBook = new Book();
// to retrieve a book
var newBookPromise = newBook.create();
newBookPromise.then(function (b) {
console.log(newBook);
});
})
.factory('Book', function ($http) {
// Book is a class which we can use for retrieving and
// updating data on the server
var Book = function (data) {
angular.extend(this, data);
}
// a static method to retrieve Book by ID
Book.get = function (id) {
return $http.get('/echo/json/').then(function (response) {
return new Book({
id: id,
name: "Foley"
});
});
};
// an instance method to create a new Book
Book.prototype.create = function () {
var book = this;
return $http.post('/echo/json/').then(function (response) {
book.id = 999;
book.name = "Joe";
return book;
});
}
return Book;
})
;