且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 AngularJS 启用/禁用锚标记

更新时间: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:

  1. href 链接在点击时不会被跟随
  2. ngClick 事件在点击时不触发
  3. 通过添加 disabled 类来更改样式
  1. href links not to be followed when clicked
  2. ngClick events not to fire when clicked
  3. 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;
}

这是正在运行的代码,包括您的示例