有些情况下,$ resource可能不适合与后端通话。这显示如何设置$ resource like行为而不使用资源。
- angular.module('myApp').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('/Book/' + id).then(function(response) {
- return new Book(response.data);
- });
- };
- // an instance method to create a new Book
- Book.prototype.create = function() {
- var book = this;
- return $http.post('/Book/',book).then(function(response) {
- book.id = response.data.id;
- return book;
- });
- }
- return Book;
- });
然后在你的控制器,你可以:
- var AppController = function(Book) {
- // to create a Book
- var book = new Book();
- book.name = 'AngularJS in nutshell';
- book.create();
- // to retrieve a book
- var bookPromise = Book.get(123);
- bookPromise.then(function(b) {
- book = b;
- });
- };