javascript 检查 Angular 指令是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18753081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:05:48  来源:igfitidea点击:

Check if an Angular directive exists

javascriptangularjs

提问by Monkey34

We're doing a lot of work around dynamic directives in our Angular project, and one thing that came up as a nice-to-have was a way to have a generic directive that can list many different types of similar objects (e.g., messages, users, comments, etc.), by delegating to specific directives based on the objects' types.

我们在 Angular 项目中围绕动态指令做了很多工作,其中一件很高兴的事情是拥有一个通用指令,该指令可以列出许多不同类型的相似对象(例如,消息、用户、评论等),根据对象的类型委托给特定的指令。

We call this directive, object-listand it will hopefully delegate to a number of different directives, if we can get it working properly.

我们称这个指令object-list为,如果我们可以让它正常工作,它有望委托给许多不同的指令。

The main issue we need to tackle is whether or not a directive that this object-listdirective has been provided exists in our system. The way we've been checking this is by issuing a $compileagainst the target directive, linking it to a scope, and checking its HTML contents (e.g., var tmpElement = $compile('<div my-message'></div>')(scope);). This seems to work when the template for the target directive is referenced by the templateoption, but when we instead try to point to a templateUrl, the HTML contents are empty.

我们需要解决的主要问题是object-list我们的系统中是否存在提供该指令的指令。我们一直在检查这一点的方法是$compile针对目标指令发出 a ,将其链接到范围,并检查其 HTML 内容(例如,var tmpElement = $compile('<div my-message'></div>')(scope);)。当目标指令的模板由template选项引用时,这似乎有效,但是当我们尝试指向A时templateUrl,HTML内容为空。

Here's a Plunker, with the templateUrlapproach in place (not working). You can comment it out and uncomment the templateline to see the alert show up.

这是一个Plunker,templateUrl方法已经到位(不起作用)。您可以将其注释掉并取消注释该template行以查看警报显示。

http://plnkr.co/edit/wD4ZspbGSo68v4eRViTp

http://plnkr.co/edit/wD4ZspbGSo68v4eRViTp

Is there another way to check the existence of a directive? I'll admit, this does seem a bit of a hack.

有没有另一种方法来检查指令的存在?我承认,这确实有点像黑客。

回答by Buu Nguyen

You can use $injector.hasto check if a provider or instance exists.

您可以$injector.has用来检查提供者或实例是否存在。

app.directive('objectList', function ($compile, $injector) {
  return {
    template: 'OK',
    link: function (scope, element, attrs) {
      var exist = $injector.has('myMessageDirective');
      ...
    }
  };
});