Skip to content

Instantly share code, notes, and snippets.

@ToastShaman
Created February 25, 2016 18:06
Show Gist options
  • Save ToastShaman/73aa4bb2cbc94ea8e8d3 to your computer and use it in GitHub Desktop.
Save ToastShaman/73aa4bb2cbc94ea8e8d3 to your computer and use it in GitHub Desktop.
Active Record Pattern (ngEurope 2014)
function OrderFactory($http) {
function Order(order) {
angular.extend(this, order || {});
this.toppings = this.toppings || {};
}
Order.prototype.addTopping = function(topping) {
this.toppings.push(topping);
};
Order.prototype.submit = function() {
return $http.post('http://pizza.example.com/orders', this)
.then(function(response){
return response.data;
});
};
Order.prototype.calculatePrice = function() {
var total = 0;
angular.forEach(this.toppings, function(topping) {
total += topping.price;
});
return total;
};
Order.getById = function(orderId) {
return $http.get('http://pizza.example.com/orders/'+orderId)
.then(function(response) {
return new Order(response.data);
});
};
return Order;
}
function OrderController(Order) {
var self = this;
self.order = new Order();
self.addTopping = function(topping) {
order.addTopping(topping);
};
self.placeOrder = function(order) {
order.submit().then(function(savedOrder) {
console.log(savedOrder);
});
};
}
angular.module('pizza-app').factory('Order', OrderFactory);
angular.module('pizza-app').controller('OrderController', OrderController);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment