Directive to find Element and replace Click Event

Here is the example code for find element (child element) using angular directive and replace it’s click event if it is a anchor tag or button. Not only replacing of events but you can do anything with the attributes if we get the element itself. So to get child element of a <div> element, i’m going to write a directive over the <div> element.

Inside the <div> element we have <a> (anchor) tag with onclick attribute. Note that this onclick attribute will have the javascript method. I don’t have the javascript method implementation in my application because consider the <a> (anchor) tag and it’s attributes are generated dynamically (it came from somewhere service). So i need to override the javascript method in AngularJS application.

Interesting..?? This is my real time issue that i faced in my project. Come lets checkout the code.

Here is the controller,

var app = angular.module('myApp',[]);
app.controller('MyCtrler', function ($scope) {
   /* write your controller code here */
})
.directive("findElement", function(){
    return {
        restrict: 'AE',
        link: function($scope, element, attrs, controller) {
                var target = element[0].querySelector('a');
                var targetElement = angular.element(target);
                targetElement.on('click', function(event){
                     alert('Im from angular click event');
                });
        }
      };
});

 

I used queryselector to get the child element <a> tag.

Check here for Multiple Filters in Controller With Example

and the HTML

<body ng-app="myApp">
<div ng-controller="MyCtrler">
     <div id="main" find-element>
         <a href="#hrefclick" onclick="javascript:void(0);">Click me for Surprise</a>
     </div>
</div>
</body>

Like this post ?!? As i shared with you that whatever i learned, love to share this post with your friends.


 

3 thoughts on “Directive to find Element and replace Click Event

  1. What’s up to all, for the reason that I am really eager of reading this website抯 post to be updated regularly. It consists of good stuff.

  2. I do accept as true with all the concepts you’ve presented to your post. They’re very convincing and will certainly work. Still, the posts are too short for novices. May you please extend them a little from next time? Thank you for the post.

Leave a Reply

Your email address will not be published.