Zack
Zack

Reputation: 13982

Prevent default behavior of a link

How would I prevent a link from automatically taking me to the next page? Essentially, I have a list of links, but first, I want to perform a check before the link is followed.

For example...

<tr ng-repeat= "match in matches">
    <td>
        <a href= {{match.link}} ng-click= "check_link(match.link)"> Click me </a>
    </td>
</tr>

What I don't know is the javascript code inside "check_link" that will prevent the user from following the link if it fails the check.

Upvotes: 0

Views: 226

Answers (3)

Kurt Funai
Kurt Funai

Reputation: 654

Personally I would create a directive in your application that easily allows you to prevent the default behaviour for links. This allows you to re-use this code any time that you want to prevent a link from behaving normally.

Example: When clicked, this link should just call the method sayHello(). It will not link to google.com

<a href="http://google.com" ng-click="sayHello()" stop-link>Say Hello</a>

Here is the code for the directive:

.directive('stopLink', function() {
  return {
    restrict: "A",
    link: function($scope, ele, attrs) {
      ele.click(function(e){
        e.preventDefault();
      });
    }
  }
});

Full working example available here: http://plnkr.co/edit/i5ZHDiwhnSVLkf59LxuU

This way, you can perform any necessary checks in sayHello(), and then use $location to redirect the user if you need to. You would likely want to use the $location.path('/blah') or $location.url('http://google.com') to change pages.

Full $location docs here: https://code.angularjs.org/1.2.16/docs/api/ng/service/$location

Upvotes: 2

MBielski
MBielski

Reputation: 6620

Your Angular function should take care of both the matching and the location redirection. Using a button tag instead of an anchor removes the automatic link following problem.

<tr ng-repeat= "match in matches">
    <td>
        <button type='button' ng-click= "check_link(match.link)"> Click me </button>
    </td>
</tr>

In your controller:

$scope.check_link = function(whatToCheck){
    if(checksOut){
        $location.path(whatToCheck);
    }
};

If you want this to appear as a link, consider using Bootstrap and give it a class of 'btn btn-link'.

Upvotes: 0

Ferdinand Torggler
Ferdinand Torggler

Reputation: 1422

<a href="{{match.link}}" ng-click="check_link(match.link, $event)">Click me</a>

You have to pass the click event (available as $event) to your check_link function. Then, if you decide to prevent it from following, call preventDefault() on it.

$scope.check_link = function (yourParam, event) {
  // your code
  if (your_condition) event.preventDefault();
  // your code
};

Upvotes: 0

Related Questions