将新指令附加到现有指令上

Attach a new Directive to an Existing one

本文关键字:指令 新指令      更新时间:2023-09-26

这是我用来创建一个新的SVG元素的函数:

makeSvg = function (tag, attrs) {
    var el = document.createElementNS("http://www.w3.org/2000/svg", tag);
    for (var k in attrs)
        el.setAttribute(k, attrs[k]);
    return el;
}

用法很简单:

var result = makeSvg("my-directive", { "data-attr": "val" });
$compile(result)($scope);

这段代码工作正常,但问题是我想添加另一个指令到产生的指令。resultcompile之前的值为:

<my-directive data-attr="val"></my-directive>

这是一个SVG元素,所以我不能像处理字符串一样处理它。我想创建如下内容:

<my-directive data-attr="val" another-directive></my-directive>

之后,我将调用compile来产生所需的结果,但我不知道如何创建指令。

只需在调用makeSvg时将其与空字符串添加到attrs对象中即可。

请看看下面的演示或在这个文件。

angular.module('demoApp', [])
	.directive('myDir', myDirective)
	.directive('anotherDirective', anotherDirective)
	.controller('MainController', MainController);
function MainController() {
}
function anotherDirective() {
	return {
    	link: function(scope, element) {
        	console.log('another directive added');
        }
    }
}
function myDirective($compile) {
    return {
        restrict: 'E',
        replace:true,
    	link: function(scope, element) {
        	var result = makeSvg("my-directive", { "data-attr": "val", "another-directive": ""});
			var compiled = $compile(result)(scope);
            element.replaceWith(compiled);
        }
    };
    
    function makeSvg(tag, attrs) {
        var el = document.createElementNS("http://www.w3.org/2000/svg", tag);
        for (var k in attrs)
            el.setAttribute(k, attrs[k]);
        return el;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp">
    <my-dir></my-dir>
</div>