Question: Angular good design pattern for implementing utility functions


Angular good design pattern for implementing utility functions

Answers 1
Added at 2016-12-24 18:12

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

Answers to

Angular good design pattern for implementing utility functions

nr: #1 dodano: 2016-12-25 23:12

I think you can create a factory since it's instantiated only once and put your functions there and inject it in a controller when you need it and assign the desired function to variable in your $scope object since any html view should be linked to a controller. and i highly recommend that you follow some angularjs style guide rules for some famous developers, try this one i believe it's the best.

style guild for angularjs 1 & style guide for angularjs 2

Source Show
◀ Wstecz