检查是否存在Angular指令 [英] Check if an Angular directive exists

查看:88
本文介绍了检查是否存在Angular指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在Angular项目中围绕动态指令做了大量的工作,并且有一件事是一个很好的方法,有一个通用指令可以列出许多不同类型的类似对象(例如,消息,用户,评论等),通过根据对象的类型委托给特定的指令。

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.

我们称这个指令,如果我们可以使它正常工作,它将有希望委托给许多不同的指令。

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

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

The main issue we need to tackle is whether or not a directive that this object-list directive has been provided exists in our system. The way we've been checking this is by issuing a $compile against 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 template option, but when we instead try to point to a templateUrl, the HTML contents are empty.

这是一个Plunker,其中有 templateUrl 方法(不工作)。您可以将其评论并取消注释模板行以查看警报显示。

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

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.

推荐答案

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

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

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

这篇关于检查是否存在Angular指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆