Skip to content

Instantly share code, notes, and snippets.

@menacestudio
Created December 7, 2014 09:46
Show Gist options
  • Save menacestudio/7bf16df56d3563f7f98d to your computer and use it in GitHub Desktop.
Save menacestudio/7bf16df56d3563f7f98d to your computer and use it in GitHub Desktop.
Angular ngResource sample
angular.module("exampleApp", []).service('exampleService', ["$http", "$q" ,function ($http, $q) {
var service = {
returnedData: [],
dataLoaded:{},
getData = function(forceRefresh)
{
var deferred = $q.defer();
if(!service.dataLoaded.genericData || forceRefresh)
{
$http.get("/api/something").success(function(data){
//service.returnedData = data;
//As Mark mentions in the comments below the line above could be replaced by
angular.copy(data, service.returnedData)
//if the intention of the watch is just to update the data
//in which case the watch is unnecessary and data can
//be passed directly from the service to the controller
service.dataLoaded.genericData = true;
deferred.resolve(service.returnedData);
});
}
else
{
deferred.resolve(service.returnedData);
}
return deferred.promise;
},
addSomeData:function(someDataToAdd)
{
$http.post("api/something", someDataToAdd).success(function(data){
service.getData(true);
});
}
};
service.getData();
return service;
}]).controller("ExampleCtrl", ["$scope", "exampleService", function($scope, exampleService){
//$scope.$watch(function() {return exampleService.returnedData}, function(returnedData){
// $scope.myModel.someData = returnedData;
//});
//if not using angular.copy() in service just use watch above
$scope.myModel.someData = exampleService.returnedData;
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment