如何从指令向元素添加新指令?

时间:2014-03-25 21:36:55

标签: javascript angularjs angularjs-directive

我有一个指令,我想在其位置添加其他指令。我能够添加新指令的属性,但它似乎没有编译并做任何事情。

我到目前为止的帽子是:plunkr

app.directive('xxx', function($compile) {
    return {
        priority: '3',
        compile: function(e, a) {
            e.removeAttr('xxx');
            a.$set('yyy','');
            return function(scope, el, attrs) {
                el.html('step 1');
                $compile(el)(scope);
            };
        }
    };
});

app.directive('yyy', function() {
    return {
        priority: '1',
        compile: function(e, a) {
            return function(scope, el, attrs) {
                el.html('step 2');
            };
        }
    };
});

app.directive('zzz', function() {
    return {
        priority: '2',
        compile: function(e, a) {
            return function(scope, el, attrs) {
                console.log('zzz');
            };
        }
    };
});

html是

<div xxx zzz></div>

当前输出为:

<div zzz yyy>Step 2</div>

这是我想要的,除了指令zzz运行两次!!那不好。

如果在添加指令yyy之后我没有在指令xxx中编译$,则yyy不执行且结果为

<div zzz>Step 1</div>

如果我在$ compile之前没有先删除xxx那么应用程序崩溃是因为我认为无限尝试编译xxx指令。

指令的优先级似乎没有任何影响。

我需要的是能够在指令中添加一个或多个指令,而不用重新编译该元素上的其他指令。

0 个答案:

没有答案