Over the time in using angular i have switched from one practive of saving state and data to another here are the two.
Please suggest me which one to continue saving and why?
angular.module('app')
.controller('personController', ['$scope', '$log',personsService, cntrl])
.factory('personsService', ['$http', '$q', service]);
//First
function cntrl($scope, $log, service){
$scope.state = {creating:false; updating:false;}
$scope.createPerson = createPerson;
$scope.person = null;
function createPerson(fn, ln, age){
$scope.state.creating = true;
service.createPerson({fn:fn, ln:ln, age:age})
.success(function(r){/*something*/})
.error(function(){/*something*/})
.finally(function(){
$scope.state.creating = true;
});
}
}
function service($http, $q){
var r = {
createPerson : createPerson
};
return r;
function createPerson(o){
return $http.post('/person/create', o);
}
}
//Second
function cntrl($scope, $log, service){
$scope.person = service.person;
$scope.state = service.state;
$scope.service = service;
}
function service($http, $q){
var state = {creating:false, updating:false};
var person = {};
var r = {
state : state,
person : person,
createPerson : createPerson
}
return r;
function createPerson(o){
state.creating = true;
var def = $q.defer();
$http.post('/person/create', o)
.success(function(dbPerson){
def.resolve(dbPerson);
angular.extend(dbPerson, person);
})
.error(function(e){
def.rreject(e);
angular.extend({}, person); //or any other logic
})
.finally(function(){
state.creating = false;
});
return def.promise;
}
}
As you can see in the
1. first example
The ajax state is maintained in the controller. and service only exposes functions that are required for that ajax state. The Person object is also maintained inside the controller so i dont have to maintain the reference to the same object as the object is directly attached to the cart. I can simpply do $scope.person = {};
2. Second Example
The ajax state is maintained by the service which now exposes the person object as well as the functions used to manipulate the object. Now i need to maintain the reference to object bby using functions sucn as angular.extend
and angular.copy
. Now the ajax state exposed by a controller is divided over multiple services. Advantages are modularity of the code and almost complete logic less controller.