Skip to content

Instantly share code, notes, and snippets.

@robwormald
Created February 16, 2014 08:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robwormald/9031381 to your computer and use it in GitHub Desktop.
Save robwormald/9031381 to your computer and use it in GitHub Desktop.
//sample Foo service.
//$http is angular's version of jq's $.ajax()
angular.module('testApp').factory('Foo',function($http){
//public Foos interface
return {
//fetch foos from the server
query : function(queryParams){
//this returns a promise
return $http.get('/api/foos',queryParams)
},
//post a new foo to the server
create : function(newFoo){
//this returns a promise
return $http.post('/api/foos',newFoo)
},
update : function(newFoo){
}
}
})
angular.module('testApp')
//inject your foo service in
.controller('SampleFooListController',function(Foo){
$scope.getBlueFoos = function(){
//fetch blue foos from the server then handle the result
//using the success promise handler will give you back the response data
Foo.query({color : 'blue'}).success(function(foos){
//assign the returned foos to scope so you can use them
$scope.foos = foos;
})
}
$scope.createNewRedFoo = function(){
//plain old JS object
var myNewFoo = {
color : 'red'
}
//using the 'then' promise handler with return the http response object.
Foo.create(myNewFoo).then(function(response){
// .data is the actual response data
console.log(response.data)
})
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment