Issue
In an Angular app, is it possible to somehow intercept all clicks on links (or all links within the scope of a particular controller's view)? For example, if I want to intercept all clicks on links, and block clicks on youtube links, can this be done?
Ideally I'd prefer not to have to add any custom attributes or use a custom element to achieve this, i.e. the links should look just like regular HTML links.
Solution
With angular, you can add a directive for the element <a>
and add a listener on 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
})
}
}
})
and Tada!
Now, if you want to block some URLs, you can access the href element inside the link function via attr.href
, so you would do it this way:
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
}
})
}
}
})
Answered By - Utopik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.