How can I disable the link to AngularJS?

My code is as follows:

    <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, the link cannot be clicked. What I was thinking of is changing the link to the button, and then styling it as a link. However, this does not work, since the button does not change the page 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>

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

+4
source share
3 answers

Here is a simple directive that catches the click event and prevents the page from transitioning based on a variable scope:

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 as follows:

<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

+7
source

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

+4

You can do this in several ways:

  • use ng-disabled
  • use ng-show
  • manipulate 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 () is the method for resolving the request URL

0
source

Source: https://habr.com/ru/post/1539153/


All Articles