更新时间:2023-12-05 21:32:34
更新:在链接函数返回中禁用 href 效果更好.以下代码已更新.
Update: Disabling the href works better in the link function return. Code below has been updated.
aDisabled
自然会在 ngClick
之前执行,因为指令是按字母顺序排序的.当 aDisabled
重命名为 tagDisabled
时,该指令不起作用.
aDisabled
naturally executes before ngClick
because directives are sorted in alphabetical order. When aDisabled
is renamed to tagDisabled
, the directive does not work.
要禁用"a"标签,我需要以下内容:
To "disable" the "a" tag, I'd want the following things:
href
链接在点击时不会被跟随ngClick
事件在点击时不触发disabled
类来更改样式href
links not to be followed when clickedngClick
events not to fire when clickeddisabled
class该指令通过模仿 ngDisabled 指令来做到这一点.根据 a-disabled
指令的值,上述所有功能都被切换.
This directive does this by mimicking the ngDisabled directive. Based on the value of a-disabled
directive, all of the above features are toggled.
myApp.directive('aDisabled', function() {
return {
compile: function(tElement, tAttrs, transclude) {
//Disable ngClick
tAttrs["ngClick"] = "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")";
//return a link function
return function (scope, iElement, iAttrs) {
//Toggle "disabled" to class when aDisabled becomes true
scope.$watch(iAttrs["aDisabled"], function(newValue) {
if (newValue !== undefined) {
iElement.toggleClass("disabled", newValue);
}
});
//Disable href on click
iElement.on("click", function(e) {
if (scope.$eval(iAttrs["aDisabled"])) {
e.preventDefault();
}
});
};
}
};
});
这里是一个 css 样式,可能表示一个禁用的标签:
Here is a css style that might indicate a disabled tag:
a.disabled {
color: #AAAAAA;
cursor: default;
pointer-events: none;
text-decoration: none;
}