seishin
seishin

Reputation: 11

performance of angularjs ng-click inside ng-repeat

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?

Upvotes: 1

Views: 1400

Answers (1)

Pavel Voronin
Pavel Voronin

Reputation: 14015

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.

Upvotes: 1

Related Questions