1

It's more a suspicion than an verified problem but..
I've worked with knockoutjs for a while and there it was a performance issue to create lots of ko click bindings - the better way was to use much fewer jQuery .on('click', ...) to handle these.

Now that I'm diving into angularjs I have a ng-repeat within ng-repeat and inside this second one I have a few buttons with ng-click..

<ul>
    <li ng-repeat="el in collection">
        <button ng-click="someFn()">click me</button>
        <button ng-click="someFn2()">click me</button>
        <button ng-click="someFn3(el)">click me</button>
    </li>
</ul>

Doesn't this create a lot of click event bindings? Or does angular optimise this somehow?

seishin
  • 19
  • 1
  • 5
  • Someone posted a directive here to do event delegation in angular (post contain a link to issue that was posted on github) http://stackoverflow.com/questions/13965627/angular-ng-click-event-delegation – GillesC Sep 07 '14 at 09:30
  • Last comment on the git issue by the creator "I always assumed event delegates must be faster and take less memory. I made some simple tests and it turns out my assumption was totally wrong! The performance of both event delegation and directly binded event handlers was almost exactly the same in my test. Thanks for the quick response. I should have researched more before opening this issue." – GillesC Sep 07 '14 at 09:31

1 Answers1

1

It's hardly any optimization in this case. What if you have several nested ngRepeats. Against which one should optimization be performed? Not easy to answer indeed. Moreover, repeated items can be controlled by another controller.

I see the following a bit hackish way of accomplishing the task.
We can apply ngClick to the parent element calling some method and passing the value allowing to identify clicked item.

<ul ng-click="itemClicked(itemIdentifier)">
    <li ng-repeat="el in collection">
        <button>click me</button>
    </li>
</ul>

The only question left to answer is how we get this identifying value. We need our own directive to apply to repeated DOM element which attaches this value to the element. After that we can get the value from $event object.

<ul ng-click="itemClicked($event.target.itemIdentifier)">
    <li ng-repeat="el in collection">
        <button click-optimiztation="el">click me</button>
    </li>
</ul>

Sure, you've to check for undefined values.

This approach must be adapted to your needs cause you want to have several clickable elements inside each repeated template. Nonetheless, I hope the idea is clear.

Pavel Voronin
  • 13,503
  • 7
  • 71
  • 137