使用AngularJS启用/禁用锚标签 [英] Enable/Disable Anchor Tags using AngularJS
问题描述
如何使用指令方法启用/禁用锚标记?
How do I enable/disable anchor tags using the directive approach?
示例:
- 在点击编辑链接时,创建&需要禁用删除或将其删除
- 在点击创建"链接时,编辑&需要禁用删除或将其删除
JAVASCRIPT:
angular.module('ngApp', []).controller('ngCtrl',['$scope', function($scope){
$scope.create = function(){
console.log("inside create");
};
$scope.edit = function(){
console.log("inside edit");
};
$scope.delete = function(){
console.log("inside delete");
};
}]).directive('a', function() {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
if(attrs.ngClick || attrs.href === '' || attrs.href === '#'){
elem.on('click', function(e){
e.preventDefault();
if(attrs.ngClick){
scope.$eval(attrs.ngClick);
}
});
}
}
};
});
推荐答案
更新: 禁用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 clicked- styles changed by adding a
disabled
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;
}
这篇关于使用AngularJS启用/禁用锚标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!