1

我想使用在控制器的相同实例之间共享的服务,但我不想为每个属性创建设置器和获取器,角度是否提供了便利?这是我想逃避的一个例子:

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;        
    };
}
4

1 回答 1

4

您可以以编程方式生成它们以使其更容易忍受:

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);
    }
}

这种情况下的用法是:

app.service('YtPlayerService', function(){
    this.playerStatus = {
        status  : 'alert',
        text    : 'Loading The Player'
    };
    generateAccessors( this, ["playerStatus"] );
});

另一个例子

var obj = {};
generateAccessors( obj, ["playerStatus", "name"]);
obj.setName(3);
obj.getName(); //3
于 2013-07-23T06:52:35.680 回答