Reputation: 119
I would like to use a service that is shared among the same instances of a controller, but i don't want to create setters and getters for each attribute, does angular provide anyway to facilitate this? here is an example of what i would like to evade :
app.service('YtPlayerService', function(){
this.playerStatus = {
status : 'alert',
text : 'Loading The Player'
};
});
app.controller("YtPlayerController", function($scope,YtPlayerService){
$scope.playerStatus = function(){
return YtPlayerService.playerStatus;
}
$scope.setPlayerStatus = function(playerStatus){
YtPlayerService.playerStatus = playerStatus;
};
}
Upvotes: 1
Views: 977
Reputation: 140228
You could generate them programatically to make it more bearable:
function generateAccessors( obj, propertyNames ) {
for( var i = 0, len = propertyNames.length; i < len; ++i ) {
var propertyName = propertyNames[i],
camelCased = propertyName.charAt(0).toUpperCase() + propertyName.substr(1);
obj[ "get" + camelCased ] = (function(propertyName){
return function() {
return obj[propertyName];
};
})(propertyName);
obj[ "set" + camelCased ] = (function(propertyName){
return function( value ) {
obj[propertyName] = value ;
};
})(propertyName);
}
}
Usage in this case would be :
app.service('YtPlayerService', function(){
this.playerStatus = {
status : 'alert',
text : 'Loading The Player'
};
generateAccessors( this, ["playerStatus"] );
});
Another example
var obj = {};
generateAccessors( obj, ["playerStatus", "name"]);
obj.setName(3);
obj.getName(); //3
Upvotes: 4