Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In AngularJS app is using plain javascript objects good or bad practice?

Suppose I need some generic object which is not dependent on AngularJS (e.g. specific collection with some special behaviours implementedd).

I could implement it completely outside AngularJS and use it in services/controllers then. I could also do it as service/factory and use it in other components.

I don't know if it is good or bad practice to write write code outside of AngularJS and then use it in the app. One big win is that while testing such code it's easier as it doesn't require AngularJS dependencies.

Do you keep whole application code in the AngularJS world in your apps?

like image 228
grafthez Avatar asked Nov 12 '22 00:11

grafthez


1 Answers

It's generally a good idea to favor the simpler approach, which in this case would be to use a plain JS object.

It will be more flexible due to less outside dependencies and there's less things to do if you want to unit test it as well.

A scenario where you might want to integrate it more deeply into angular is if it actually requires some dependency injection or other such features provided by angular, but if it does its job without any of that then I don't really see a reason to mix them up.

If you wanted to do it as a plain JS object and then perhaps inject it using angular's DI system to one of your angular components, it would be pretty straightforward to wrap the object into a factory separately for this.

like image 135
Jani Hartikainen Avatar answered Nov 14 '22 22:11

Jani Hartikainen