gpt4 book ai didi

angularjs - 使用 AngularJS 启用/禁用 anchor 标记

转载 作者:行者123 更新时间:2023-12-02 19:51:13 26 4
gpt4 key购买 nike

如何使用指令方法启用/禁用 anchor 标记?

示例:

  1. 点击编辑链接时,需要禁用或灰显“创建和删除”
  2. 点击“创建链接”时,需要禁用或灰显“编辑和删除”功能

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);
}
});
}
}
};
});

LINK to CODE

最佳答案

更新:在链接函数返回中禁用 href 效果更好。下面的代码已更新。

aDisabled 自然会在 ngClick 之前执行,因为指令按字母顺序排序。当 aDisabled 重命名为 tagDisabled 时,该指令不起作用

<小时/>

要“禁用”“a”标签,我需要以下内容:

  1. href 链接点击后不被跟踪
  2. ngClick 事件在点击时不触发
  3. 通过添加 disabled 类更改样式

该指令通过模仿 ngDisabled 指令来实现此目的。根据 a-disabled 指令的值,以上所有功能都会被切换。

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 样式:

a.disabled {
color: #AAAAAA;
cursor: default;
pointer-events: none;
text-decoration: none;
}

And here is the code in action, with your example

关于angularjs - 使用 AngularJS 启用/禁用 anchor 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23425254/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com