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'
            })
        }
}])

-- 
You received this message because you are subscribed to the Google Groups 
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply via email to