samedi 24 décembre 2016

Angular good design pattern for implementing utility functions

I searched for a lot of design patterns, but found nothing on how to implement functions that are going to be used both in some controllers and in html markup. I really want to escape copy-pasting functionality, so here goes the problem.

I have some items stored in localStorage as an Array of entitites, each of which has a price, quantity and discount. Call that array a cart of items. In a certain page I need to interpolate the sum of the prices as an "overall price". That is the 'cart displaying page', which is basically a list of items from the cart. On the other hand, I have an 'order page' with a form, in which the overall price should also be shown. Say this pages are manipulated with two different controllers: OrderController and CartController, in both of which I have a function called calculatePrice, which returns the overall sum, which is then interpolated inside the html in both order.html and cart.html.

So it happens I already did some copy-pasting. And if (which is possible in the nearest future) I have another controller/view which needs this function, I'll end up copy-pasting again.

My thoughts on this:

1) Create a $rootScope function calculatePrice and just use it as is, both inside controllers and the view. Undesired, don't want to insert too much imperative code inside the 'run' cycle of my app

2) Create a service for utility functions, inject it inside the controllers and only declarative style like '$scope.someFunction = service.someFunction'

3) Create a service, inject it inside the app.run function and connect it to rootScope

But I don't think any of this is right. I want to find the most possible clean solution.

Aucun commentaire:

Enregistrer un commentaire