I’m finding this kind of relationship in my apps a lot, and I’d love some critiques/warnings/best practices ideas from you folks. Kinda made it up as I went along, and now I’m wondering if it’s the best way? I’ve left out some functionality (like update, delete, find individual thing, etc) from the service, but I wanted to simplify the idea to make it easier for you to respond. Thanks for the insight.
controller:
.controller(’ThingController', ['$scope', ‘ThingService’,
function($scope, ThingService) {
$scope.model = {};
$scope.model.things = ThingService.getThings();
ThingService.loadThings();
$scope.create = function() {
ThingService.create();
ThingService.ready().then(
function() {$scope.model.things = ThingService.getThings(); } //refresh array
}
}
}])
service:
.factory(’ThingService', ['$q', ‘api-service',
function($q, apiSvc) {
var model = {};
var loaded = $q.defer();
model.things = [];
return {
loadThings: loadThings,
ready: function() {
return loaded.promise;
},
getThings: function() {
return model.things;
},
create: function(thing) {
loaded = $q.defer();
apiSvc.createThing(thing).then(function(result) {
model.things.push(result.data);
resolve();
});
}
};
function loadThings(userID) {
loaded = $q.defer();
apiSvc.getThings(userID).then(function(result) {
angular.copy(result.data, model.things);
resolve();
});
}
function resolve() {
return loaded.resolve()
}
}])
api-service:
.factory('APIService', ['$http’, function($http) {
getThings: function(credentials) {
return $http({
method: “get",
url: ‘
http://website.com/getThings'
})
}
}])