我可以定义一个影响所有< a>的指令.文档中的元素如下:
myApp.directive('a',function() { return { restrict: 'E',link: function(scope,element) { // Some custom logic to apply to all <a> elements } }; });
我可以这样做,但对于匹配给定CSS选择器的元素?像这样?
myApp.directive('a[href^="mailto:"]',element) { // Some custom logic to apply to all <a> elements // w/ a href attribute starting in "mailto:" } }; });
解决方法
没有.
当您将特定名称下的指令angular puts指向新名称下的指令高速缓存时,或将其推送到指定名称下已有指令的列表.
之后,角度搜索通过查找指令与(tagName | attrName | className | commentName)之间的对应关系,并在找到角度调用时编译列表中每个指令的函数,并将找到的(元素,attrs)作为参数传递给编译函数.
所以在你的情况下,[href ^ =“mailto:”]将被搜索为’< a [href ^ =“mailto:”]>< / a [href ^ =“mailto:”]>‘这显然是不存在的,属性,类和注释也是如此.
在您的情况下,最理智的解决方案是:
myApp.directive('a',element,attrs) { if (attrs.href.indexOf('mailto:') !== 0) { return; } // Some custom logic to apply to all a[href^="mailto:"] elements } }; });