Ian Steffy Ian Steffy - 4 months ago 47
AngularJS Question

href and ng-click do not work in the same tag on Mobile

href and ng-click are not both called if used in the same or overlapping tags in Mobile but work perfectly on the desktop. My guess is

touch
is what is breaking this.

Example:

<a href="/" ng-click="playSound()"> link </a>


-or-

<div ng-click="playSound()">
<a href="/"> link </a>
</div>


Both href and ng-click are called in Desktop views but only called
playSound()
using mobile's touch.

What I want to achieve: I want to be able to link to the next page and also call the playSound() function on touch. Currently, ng-click overrides href on touch and I am never linked to the next page.

Answer

I have run into the same issue and found the answer here.

In a nutshell, you can have multiple directives with the same name and both will get run when they are called. this allows you to write a custom directive, also called ng-click, which requires less work than going through all of your links and moving the redirect to the function called by ng-click.

Here's the code:

angular.module('ngClick', function( $location ) {
  return {
    link: function(scope, elem, attrs) {
      if(attrs.href) {
        elem.on('touchend', function() {
          $location.path(attrs.href);        
        });
      }
    },
    priority: 1
  };
});

For me, it was simple enough to move the redirect into my function and redirect the page using $location:

$location.path('www.my-link.com');
Comments