我在指令和属性名称冲突时遇到了问题。这是我的问题的简化版本:有两个指令,其中第一个指令的名称是第二个指令的属性名称:

angular.module('mymodule').directive('property', function() {
    return {
        template: '<div>Property Directive</div>'
    };
});

angular.module('mymodule').directive('fail', function() {
    return {
        scope: {
            property: '='
        },
        template: '<div>{{property}}</div>'
    }
});


当我尝试将第二条指令添加到html文件时:

<fail property="'test'"></fail>


我收到以下错误:

Error: [$compile:multidir] Multiple directives [fail, property] asking for template on: <fail property="'test'">http://errors.angularjs.org/1.3.0-rc.4/$compile/multidir?p0=fail&p1=property&p2=template&p3=%3Cfail%20property%3D%22'test'%22%3E


现在,如果两个指令都在我的模块中,这将不是问题,因为重命名它们很容易。但是我在应用程序中使用的不同外部模块的指令/属性名称冲突。

如何在特定情况下告诉angular属性property不是指令?

最佳答案

只是将我的评论扩展为答案,而不是按照我能想到的方式重命名该指令,而是创建同一指令的副本并使现有指令无效。这样,您就可以为从另一个模块使用的名称不正确的指令设置适当的命名约定。在这里你需要


$compileProvider


要注册新指令,请重写角度指令构造函数app.directive

$provide service


要用较差的名称修饰指令,请获取其定义,然后仅返回空白的空操作工厂。
您可以使用Directive关键字修饰指令postFixing。他们还注册为工厂。



您需要确保此配置,尤其是装饰部件在目标指令注册后出现。

app.config(['$compileProvider', function ($compileProvider) {
    //Override directive constructor
    app.directive = function (name, dirObject) {
        //Register a directive
        $compileProvider.directive(name, function() {
           return dirObject[0];
        });
    };
}]).config(['$provide', function($provide){
    //Decorate target directive
    $provide.decorator('propertyDirective', ['$delegate', function($delegate){
        //Just register a new directive with source's definition
        app.directive('cmProperty', $delegate);
        //return a no operation factory as directive constructor, to make it inactive
        return function() { return angular.noop };
    }]);
}]);


Demo

您可以通过将目标指令名称放置在常量中并运行装饰器循环以自动为其前缀/重命名(使用其他名称重新创建)来实现此目的。



更新资料

查看generic solution in my repository

09-10 09:54
查看更多