如何禁用AngularJS链接?

时间:2014-05-04 07:44:01

标签: angularjs

我的代码如下所示:

    <a ng-disabled="!access.authenticated"
            data-ng-class="{ 'current': $state.includes('home'), 'disabled': !access.authenticated } "
            href="/home/overview"
            title="Home">
        <i class="fa fa-home fa-fw"></i>
    </a>

我想这样做,以便当access.authenticated为false时,无法单击该链接。我想到的是将链接更改为按钮,然后将其设置为链接样式。但是这不起作用,因为按钮不会导致页面URL更改。

    <button ng-disabled="!access.authenticated"
            data-ng-class="{ 'current': $state.includes('home'), 'disabled': !access.authenticated } "
            href="/home/overview"
            title="Home">
        <i class="fa fa-home fa-fw"></i>
    </button>

有人可以告诉我如何做我需要的事吗?

3 个答案:

答案 0 :(得分:8)

这是一个简单的指令,它拦截click事件并阻止基于范围变量的页面转换:

module.directive('myLink', function() {
  return {
    restrict: 'A',
    scope: {
      enabled: '=myLink'
    },
    link: function(scope, element, attrs) {
      element.bind('click', function(event) {
        if(!scope.enabled) {
          event.preventDefault();
        }
      });
    }
  };
});

你可以像这样使用它:

<a my-link="linkEnabled" data-ng-class="{'disabled': !linkEnabled}" href="/home/overview">
  <i class="fa fa-home fa-fw">Link</i>
</a>

Here is a demo

答案 1 :(得分:5)

的CSS:

 .inactive {
   color: #ccc;
   pointer-events: none;
   cursor: default;
 }

HTML:

<a href="some.html" ng-class="access.authenticated ? '' : 'inactive'">some link</a>

查看this fiddle

答案 2 :(得分:0)

您可以通过多种方式实现:

  • 使用ng-disabled
  • 使用ng-show
  • 使用网址进行操作

<a ng-disabled="!access.authenticated" href="/home/overview"><i class="fa fa-home fa-fw"></i></a>

<a ng-show="access.authenticated" href="#"><i class="fa fa-home fa-fw"></i></a> <a ng-show="!access.authenticated" href="/home/overview"><i class="fa fa-home fa-fw"></i></a>

<a href="{{getUrl(access.authenticated)}}"><i class="fa fa-home fa-fw"></i></a> - 其中getUrl() - 解析请求网址的方法

相关问题