Sounds like you want something like this: (essentially $resource)
angular.module('myApp',[])
.factory('MasterDataService',function($http){
var currentUser = {};
return {
getCurrentUser: function(any,param,you,need){
currentUser.$promise = $http({...}).then(function(response){
var mainpulateUser = response.data;
//do business logic,
return angular.extend(currentUser,manipulatedUser);
});
return currentUser;
}
};
})
.controller('myCtrl',function(MasterDataService,$scope,$log){
$scope.buttonTitle = 'UpdateUser';
$scope.user = MasterDataService.getCurrentUser();
$scope.user.$promise.then(function(user){
$log.debug($scope.user === user);
$log.debug('current user -> ',$scope.user);
});
$scope.getCurrentUser = function(){
MasterDataService.getCurrentUser();
}
});
Here is a plunker. (I use $timeout
to mock $http
) The key is to maintain one reference to your current user.
That is why MasterService.getCurrentUser();
actually updates the user. Its all just var currentUser = {}
. That reference never gets removed. hence $scope.user === currentUser
Ideally though You don't want to do business logic in your data-retrieval service or your controller. But your model. To define a model you might do something like...
angular.factory('User',function(){
var User = function(initWith){
initWith = initWith || {};
this.firstName = initWith.firstName || ''
this.lastName = initWith.lastName || ''
this.position = 'employee'
this.lastRetrieved = new Date();
}
User.prototype.doBusinessLogic = function(position){
this.position = position;
}
return User;
});
Here is a forked plunk.