0

is there any better way of handling clicks inside a controller than this?

<div ng-controller="SomeController>
  <a href="/#!/something" ng-click="doTheSame()">link1</a>
  <a href="/#!/something" ng-click="doTheSame()">link2</a>
  <a href="/#!/something" ng-click="doTheSame()">link3</a>
  ..
  <a href="/#!/something" ng-click="doTheSame()">link99</a>
</div>

in jQuery I would do something like:

$('div > a').on('click', function() {
  // do some stuff
});
2
  • What are you looking for exactly? A generic way to add doTheSame() to every link inside a page or div? Commented Jun 22, 2015 at 15:35
  • yes, I updated my question with jQuery example Commented Jun 22, 2015 at 15:36

1 Answer 1

3

You don't really want to handle any DOM stuff in controllers (a controller just ties data to the view, which happens to be the DOM).

You want to use a directive for DOM manipulation. (However, yes, ng-click is a built-in directive that can run methods inside the controller).

If you'd like to attach some behavior to an element, you can do something like this:

myApp.directive('myDirective', myDirective);

myDirective.$inject = ['whateverService'];

function myDirective(whateverService) {
    var d = {
        restrict: 'A',
        link: link
    };

    return d;

    function link(scope, $el, attrs) {
        $el.on('click', doSomething);

        function doSomething() { /* ... */ }
    }
}

HTML:

<div myDirective></div>

See John Papa's style guide for more info.

You can have multiple of these directives, and you can even pass in data:

<div myDirective="first-link">First</div>
<div myDirective="second-link">Second</div>
<!-- etc. -->
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.