Javascript 角度JS中的动态配置

Javascript 角度JS中的动态配置,javascript,angularjs,Javascript,Angularjs,我正在创建一个显示图表的指令。 我用一个指令浏览了创建模块的常用模板。对于配置,我决定使用提供者。 我了解如何让应用程序通过提供程序设置模块的配置 然而,我拥有的一个用例是,配置可以在运行时根据用户的首选项进行更改。 如何使模块能够为客户端API提供在运行时修改配置的方法 是否也可以将ProviderConfiguration注入客户端的控制器?他们的这种方法有什么明显的缺点吗 当前代码模板如下所示 //Provider angular.module('foobar', []).provider

我正在创建一个显示图表的指令。 我用一个指令浏览了创建模块的常用模板。对于配置,我决定使用提供者。 我了解如何让应用程序通过提供程序设置模块的配置

然而,我拥有的一个用例是,配置可以在运行时根据用户的首选项进行更改。 如何使模块能够为客户端API提供在运行时修改配置的方法

是否也可以将ProviderConfiguration注入客户端的控制器?他们的这种方法有什么明显的缺点吗

当前代码模板如下所示

//Provider
angular.module('foobar', []).provider('foobarConfig', [function() {
    var config = {
        //config properties here.
    }
    var configurationProvider = {
        //Getters and Setters that work on 'config'.
        setProperty(prop, value) {
            if(config[prop] !== undefined) {
                config[prop] = value;
            }
        },
        getProperty(prop) {
            return config[prop];
        },
        $get: function() {
            return this;
        }
    }
    return configurationProvider;
}

//Chart Directive.
angular.module('foobar').directive('foobarChart', ['foobarConfig', function(foobarConfig) {
    //Can use the foobarConfig here.
}]);

angular.module('clientApp', [ 'foobar'])
.config(['foobarConfigProvider', function(foobarConfigProvider) {
    //Can provide the initial configuration to the module here.
    foobarConfigProvider.setProperty("foo", "bar");
}]);

angular.module('clientApp').directive('clientFoo', function() {

    //What should be done to change foobarConfig here?
});

是的,它是配置服务的完美有效配方,在配置和运行阶段都可用,因此
foobarConfigProvider.setProperty(“foo”,“bar”)
foobarConfig.setProperty(“foo”,“bar”)
可以以相同的方式使用

对于没有依赖项的配置服务,
常量
是更方便的选择:

.constant('foobarConfig', (function () {
    var config = {
        // ...
    };

    return {
        setProperty: function (prop, value) {
            if(config[prop] !== undefined) {
                config[prop] = value;
            }
        },
        getProperty: function (prop) {
            return config[prop];
        }
    };
})());
对于具有有限配置键集的ES5兼容解决方案,可以使用带有和的
constant
对象,这样就不需要自定义getter/setter函数<代码>对象。定义属性可以在初始
配置
对象上迭代,因此不需要样板描述符代码:

.constant('foobarConfig', (function () {
    var config = {
        // ...
    };

    var obj = {};

    angular.forEach(config, function (value, key) {
        Object.defineProperty(obj, key, {
            enumerable: true,
            writable: true,
            value: value
            // no 'get' and 'set' are required if the only purpose for
            // them is to restrict a set of config keys
        })
    });

    Object.seal(obj);

    return obj;
})());

请注意,
constant
的主要区别(以及可能的缺点)在于服务价值正在被急切地定义,
foobarConfig
将是不同喷油器的相同对象。通常生产没有区别,但这可能(也可能不会)影响测试。

感谢您介绍如何使用
常量
替代方案。