在超链接中包装 html 元素的指令

Directive to wrap html element in hyperlink

我想编写自己的指令,它可以使用传递的参数在超链接中包装任何 html 元素,例如:

<button myDirective="parameter">...</button>

会有以下效果

<a href="url/parameter"><button>...</button></a>

我是 AngularJS 的初学者。不幸的是,我没有在 typescript.

中找到任何有用的教程来制作这个

我创造了这样的东西:

export default class LinksHelperDirective implements ng.IDirective {
public static Name = "kb-link";
public restrict = "A";
public urlTemplate = "";

constructor(private readonly $parse: ng.IParseService) {
}

public static Factory() : any {
    const directive = ($parse: ng.IParseService) => {
        return new LinksHelperDirective($parse);
    };

    directive["$inject"] = ["$parse"];
    return directive;
}

link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes,
    ngModel: ng.INgModelController) => {
    const linkId = this.$parse(attrs["kb-link"])(scope);
    const wrapper = angular.element('<a href="https://support/' + linkId + '"></a>');
    element.wrap(wrapper);
};

}

但不幸的是它不起作用...甚至没有调用构造函数。我在索引文件中注册了指令,如下所示:

module.directive(LinksHelperDirective.Name, LinksHelperDirective.Factory(), ["$parse"]);

并在 html 文件中:

<button kb-link="1234">Help</button>

有人知道这有什么问题吗?

您需要为此使用 ng-transclude 指令

class WrapDirective {
  restrict = 'E';
  transclude = true;
  scope = { someLink: '<' };
  template: '<a ng-href="url/{{ someLink }}"><ng-transclude></ng-transclude></a>';
}

但是你需要像 <wrap-directive some-link="$ctrl.link"><button>...</wrap-directive>

一样包装你的元素