4

My code looks like this:

    <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>

I want to make it so that when access.authenticated is false then the link cannot be clicked. What I thought of was changing the link to a button and then styling it like a link. However this does not work as a button does not cause the page URL to change.

    <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>

Can someone tell me how I can do what I need ?

  • I think you could try something like this by writing a custom directive: http://stackoverflow.com/questions/23366134/how-to-stop-ng-click-from-a-custom-directive-in-angularjs/23367853#answer-23367853 and use preventDefault – Khanh TO May 04 '14 at 07:54
  • Hi Royi - Can you explain what you mean with your comment. Note that I am using ui-router. Not sure if that makes a differnce. Thanks –  May 04 '14 at 08:06
  • he says you should switch fro href to ng-href or data-ng-href – Ronni Skansing May 04 '14 at 08:49
  • 1
    Why should they use `ngHref` here? There is no binding in their `href` value. `ngHref` will do *nothing* here. – Steve Klösters May 04 '14 at 12:49

3 Answers3

8

Here is a simple directive which intercepts the click event and prevents the page transition based on a scope variable:

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

You can use it like this:

<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

Sebastian
  • 16,813
  • 4
  • 49
  • 56
5

css:

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

html:

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

Check out this fiddle.

Kludge
  • 2,653
  • 4
  • 20
  • 42
-1

You can do it in several ways:

  • use ng-disabled
  • use ng-show
  • manipulate with URL

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

or

<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>

or

<a href="{{getUrl(access.authenticated)}}"><i class="fa fa-home fa-fw"></i></a> - where getUrl() - method for resolving request url

Lugaru
  • 1,430
  • 3
  • 25
  • 38