指令名称和属性名称冲突

时间:2014-10-17 00:47:30

标签: angularjs

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

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

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

如何判断角度,在这种特殊情况下属性property并不是指令?

1 个答案:

答案 0 :(得分:2)

只是扩展我的评论来回答,而不是在我想到的方式上重命名指令是创建同一指令的副本并使现有指令无效。这样,您可以为从另一个模块使用的命名不佳的指令具有正确的命名约定。在这里你需要

  • $compileProvider

    • 要注册新指令,请覆盖angular指令构造函数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