angularjs 拦截链接点击

nhhxz33t  于 7个月前  发布在  Angular
关注(0)|答案(3)|浏览(64)

在一个Angular应用中,是否有可能拦截所有对链接的点击(或特定控制器视图范围内的所有链接)?例如,如果我想拦截所有对链接的点击,并阻止对youtube链接的点击,这可以做到吗?
理想情况下,我不喜欢添加任何自定义属性或使用自定义元素来实现这一点,即链接应该看起来像常规的HTML链接。

yxyvkwin

yxyvkwin1#

使用angular,您可以为元素<a>添加一个指令,并在click上添加一个侦听器

app.directive('a', function() {
    return {
        restrict: 'E', // only Elements (<a>),
        link: function(scope, elm, attr) {
            // every time you click on the link
            elm.on('click', function($event) {
                console.log('event')
                $event.preventDefault()
                return false
            })
        }
    }
})

字符串
多田!
现在,如果你想阻止一些URL,你可以通过attr.href访问link函数中的href元素,所以你可以这样做:

app.directive('a', function() {
    return {
        restrict: 'E', // only Elements (<a>),
        link: function(scope, elm, attr) {
            // every time you click on the link
            elm.on('click', function($event) {
                // only some URLs
                if(attr.href.match(/youtube\.com/)) {
                    $event.preventDefault()
                    return false
                }
            })
        }
    }
})

6jygbczu

6jygbczu2#

这个解决方案使用vanilla JS:

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll('a').forEach(a => {
    a.addEventListener("click", (event) => {
      event.preventDefault(); // Block the page from loading
      alert(a.href); // Show an alert with the url in the href
    })
  })
});

个字符

6vl6ewon

6vl6ewon3#

我为此做了一个基于jQuery的示例。

// Contents, Controls or document ready 
$(document).ready(function(){
  $('.block').find('a').each ( function(){
      $(this).click(function(){
      	  console.log('custom-action');
          return false;
      });
  });
});

个字符

相关问题