oxfn
oxfn

Reputation: 6860

Bind function result to angular repeat

I have a service instance in my $scope and walk through result of it's method in ng-repeat

In controller:

$scope.svc = MyService;

In template:

<tr ng-repeat="items in svc.getAll()">
    <!-- ... -->
    <td><button ng-click="svc.remove($index)">X</button></td>
</tr>

It is handy, thus I can point ng-click directly to service methods without dumb wrappers. But doesn't it make Angular engine work less effective than if it's binded to array? I have traced get calls, it is triggered 2 times on each $scope change. It's not much but maybe there're any weird pitfalls of using ng-repeat this way?

Upvotes: 0

Views: 898

Answers (1)

dirkk
dirkk

Reputation: 6218

No, there should not be any real performance impact. The most resources in the repeat are required because of the data-binding.

But data-binding is also done when you use an array directly. It doesn't matter whether it is included directly or returned by a function. The only overhead should be the function call and return of the array, but this is negligible.

However, I would advice against binding a service directly to the controller, this is bad practice. Consider you are using a service function multiple times in the template and you then decide to rename the function - You would have to change it multiple times as well, not only once in the appropriate wrapper function. Also, you will automatically expose all service functions to the template, although you might just need a subset (i.e. if you have an initialization function, which is called in the controller you most likely do no want it to be called anywhere again in the template).

Upvotes: 1

Related Questions