简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM