//Syntax allows to chain factories
angular.module('cellar.services', ['ngResource']).
//The factory returns objects / functions that can be used by the controllers
factory('Wine', ['$resource', '$http', '$rootScope', function($resource, $http, $rootScope){
return {
//the resource provider interacting with the PHP backend
api:
$resource('api/wines/:wineId', {}, {
update: {method:'PUT'}
}),
/*
* A generic function that can be called to emit an event on one ctrl that can be handled by another ctrl.
* The WineDetailCtrl emits it on each save, update or delete request, so that the WineListCtrl can react and update itself.
*/
broadcastChange: function(){
$rootScope.$broadcast('handleBroadcast');
}
}
}])
function WineListCtrl(Wine, $location, $scope) {
$scope.wines = Wine.api.query();
$scope.$on('handleBroadcast', function() {
$scope.wines = Wine.api.query();
});
}
WineListCtrl.$inject = ['Wine', '$location', '$scope'];
function WineDetailCtrl(Wine, $routeParams, $location, $scope) {
$scope.wine = Wine.api.get({wineId: $routeParams.wineId})
$scope.saveWine = function () {
if ($scope.wine.id > 0)
{
Wine.api.update({wineId:$scope.wine.id}, $scope.wine, function (res) {
alert('Wine ' + $scope.wine.name + ' updated');
Wine.broadcastChange();
$location.path("/wines");
}
);
}
//no match for wine means it's an empty form
else
{
Wine.api.save({}, $scope.wine, function (res) {
alert('Wine ' + $scope.wine.name + ' created');
Wine.broadcastChange();
$location.path("/wines");
}
);
}
}
$scope.deleteWine = function () {
Wine.api.delete({wineId:$scope.wine.id}, function(wine) {
alert('Wine ' + $scope.wine.name + ' deleted')
Wine.broadcastChange();
$location.path("/wines");
});
}
}
WineDetailCtrl.$inject = ['Wine', '$routeParams', '$location', '$scope'];
scotchApp.controller('CompanyListCtrl', function ($scope, $http) {
$http({
url: "api/companies",
cache: true,
method: "GET"//,
//data: {"foo":"bar"}
}).success(function(data, status, headers, config) {
$scope.companies = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
});