dontHaveName
dontHaveName

Reputation: 1937

angular.js - simplest way to handle click inside controller

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
});

Upvotes: 0

Views: 110

Answers (1)

Josh Beam
Josh Beam

Reputation: 19772

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. -->

Upvotes: 3

Related Questions