I have an Angular application. Its working good, but as my application is getting bigger I'm worried about the large number of dependencies that I have to inject in each controller.
for example
app.controller('viewapps',[
'$scope','Appfactory','Menu','$timeout','filterFilter','Notice', '$routeParams',
function($scope,Appfactory,Menu,$timeout,filterFilter,Notice,$routeParams) {
//controller code..
}])
I am sure that the list of dependencies are going to increase in future. Am I doing something wrong here? Is this the right approach? What is the best way to effectively handle this?
There are only three ways a component (object or function) can get a hold of its dependencies: The component can create the dependency, typically using the new operator. The component can look up the dependency, by referring to a global variable. The component can have the dependency passed to it where it is needed.
It relieves a component from locating the dependency and makes dependencies configurable. It also helps in making components reusable, maintainable and testable. AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.
Dependency Injection in AngularJS can be defines as the software design pattern which defines the way the software components are dependent on each other. AngularJS provides a set of components that can be injected in the form of dependencies such as factory, value, constant, service, and provider.
The "Application Module" can be injected as a dependency in AngularJS.
It's hard to be specific without an exact use case, or seeing the exact code in your controller, but it looks like your controller might be doing too much (or might end up doing too much as you add things later). 3 things you can do:
Delegate more of the logic to service(s) that are injected in.
Separate out into different controllers, so each only has (just about) 1 responsibility.
Separate out into directives, each with their own controllers and templates, and allow options to be passed in, and output given out, via attributes and the scope
option of the directive. This is often my preferred option, as you end up building a suite of reusable components, each with a mini-API.
It is fine for directives to be used like this, at least in my opinion. They aren't just for handling raw Javascript events, or accessing the DOM directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With