1

我正在寻找包含 Angular 指令/模块的全局选项。

我可以.constant()在我的模块文件中使用一个(或简单的配置对象),但由于该模块是为其他人设计的,可以包含在他们的项目中,并且可以通过 Bower 安装,我不喜欢全局选项被吹的想法当模块得到更新时离开。我知道.constant()可以包含在另一个文件中,但是用户必须包含它 - 我更希望模块包含所有内容(默认值),然后用户可以根据需要扩展/修改。

我正在设想一种与 jQuery 插件模式类似的方法,例如:

$('.myElement').myPlugin({
    option1: '',
    option2: ''
});

插件

(function($) {
    $.myPlugin = function( element, conf ) {
        var $element = $(element);
        var defaults = {
            option1: '',
            option2: '',
        };
        var config = $.extend( defaults, conf );

        //...

    };

    $.fn.myPlugin = function(config) {
        return this.each(function() {
            if (undefined == $(this).data('myPlugin')) {
                var plugin = new $.myPlugin(this, config);
                $(this).data('myPlugin', plugin);
            }
        });
    };
})(jQuery);
4

1 回答 1

2

您的应用程序和配置模块

这是我们可以定义配置块并注入提供程序的地方。从这里我们可以设置我们的配置选项。

var myApp = angular.module( 'myApp', ['myModule'] )

myApp.config( function( myDirectiveConfigProvider ) {
    myDirectiveConfigProvider.config = {
        option1: 'A new setting'
        //option2: 'A new setting'
    };

    // OR

    myDirectiveConfigProvider.config.option1 = 'A new setting';
    //myDirectiveConfigProvider.config.option2 = 'A new setting';
});

模块

在模块中,我们可以定义一个服务来保存我们的默认配置选项。如果您不想注入它,这也可以简单地包含在指令中var config = {}

我们还定义了一个 Provider,它将被注入到我们的配置块中。

在指令中,我们只需要使用提供者扩展config(注入的服务或变量)。

angular.module( 'myModule', [] )

    .value( 'config', {
        'option1': 'my default setting',
        'option2': 'my default setting'
    })


    .directive( 'myDirective', [ 'config', 'myDirectiveConfig', function( config, myDirectiveConfig ) {
        return {
            link: function( scope, element, attrs ) {

                angular.extend( config, myDirectiveConfig.config );

                console.log( config.option1 ); //'A new setting'
                console.log( config.option2 ); //'my default setting'
            }
        }
    }])

    .provider( 'myDirectiveConfig', function() {
        var self = this;
        this.config = {};
        this.$get = function() {
            var extend = {};
            extend.config = self.config;
            return extend;
        };
        return this;
    });
于 2014-04-07T04:20:33.980 回答