我可以定义一个影响所有 <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:"]', function() {
return {
restrict: 'E',
link: function(scope, element) {
// Some custom logic to apply to all <a> elements
// w/ a href attribute starting in "mailto:"
}
};
});
最佳答案
不。
当您在特定名称下注册指令时,angular 会将指令放入新名称下的指令缓存中,或将其推送到指定名称下的现有指令列表中。
之后,angular 搜索 dom 以找到您的指令和 (tagName|attrName|className|commentName) 之间的对应关系,当找到时,angular 调用列表中每个指令的 compile 函数,并将找到的 (element, attrs) 作为参数传递给 compile 函数.
所以在你的情况下 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
}
};
});
关于angularjs - 我可以制作一个 Angular 指令来匹配 CSS 选择器(不仅仅是标签名称)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21146394/