我可以制作一个Angular指令来匹配CSS选择器(而不仅仅是标签名称)吗?

Dan*_*Tao 5 angularjs angularjs-directive

我可以定义一个影响<a>文档中所有元素的指令,如下所示:

myApp.directive('a', function() {
  return {
    restrict: 'E',
    link: function(scope, element) {
      // Some custom logic to apply to all <a> elements
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

我可以这样做,但对于匹配给定CSS选择器的元素?像这样?

myApp.directive('a[href^="mailto:"]', function() {
  return {
    restrict: 'E',
    link: function(scope, element) {
      // Some custom logic to apply to all <a> elements
      // w/ a href attribute starting in "mailto:"
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

Kar*_*yan 0

不。

当您以特定名称注册指令时,Angular 会将指令放入新名称下的指令缓存中,或将其推送到指定名称下的现有指令列表中。

之后,Angular 会搜索 dom 来查找指令与 (tagName|attrName|className|commentName) 之间的对应关系,当找到时,Angular 会调用列表中每个指令的编译函数,并将找到的 (element, attrs) 作为参数传递给编译函数。

因此,在您的情况下,a[href^="mailto:"]将按原样搜索'<a[href^="mailto:"]></a[href^="mailto:"]>',这显然是不存在的,对于属性、类和注释也是如此。

对于您的情况,最明智的解决方案是:

myApp.directive('a', function() {
  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
        if (attrs.href.indexOf('mailto:') !== 0) { return; }
        // Some custom logic to apply to all a[href^="mailto:"] elements
    }
  };
});
Run Code Online (Sandbox Code Playgroud)