krex
krex

Reputation: 345

AngularJS fire function on-click anchor links

I'm hoping someone can help me achieve a clean and effective way of firing a function when anchor links, with a specific css class, are clicked.

I could do this using ng-click but I feel that is a bit of a messy and unmaintainable solution: it would mean adding ng-click to each of the anchor links I want to track.

My navigation links currently look like this:

<li id="item1" class="foo"><a href="#/item1">CLICK ME</a></li>

I'd like to emulate the functionality of ng-click in a similar manner to the following JQuery stubb (which doesn't seem to work in my configuration):

$('.foo a').on('click', function(){
    //do some code 
});

tl;dr

I'd like an AngularJS way to execute a function when an element with a specific css class is clicked.

Please let me know if I haven't described this well enough.

Thanks in advance,

JohnD

Upvotes: 0

Views: 1748

Answers (2)

runTarm
runTarm

Reputation: 11547

You could write a custom directive like this:

.directive('foo', function () {
  return {
    restrict: 'C',
    link: function (scope, element, attrs) {
      element.on('click', 'a', function (e) {
        console.log('clicked! do some code here.');
      });
    }
  }
});

Example Plunker: http://plnkr.co/edit/53gge6KUoEoedt1PD0RB?p=preview

Upvotes: 1

Darshan P
Darshan P

Reputation: 2241

You could write directive and apply it to root element.

DEMO

<div ng-app="app" foo-dir>
    <li id="item1" class="foo"><a href="#/item1">CLICK ME 1</a>

    </li>
    <li id="item2" class="foo"><a href="#/item2">CLICK ME 2</a>

    </li>
</div>

javascript

var app = angular.module("app", []);

app.directive("fooDir", function () {
    return {
        link: function ($scope) {
            $(".foo a").on("click", function (event) {
                alert($(this).html());
            });
        }
    }
});

Upvotes: 3

Related Questions