Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS dependency-injection

I have say two modules:

  1. foo.a
  2. foo.b

and an application module:

  angular.module("foo", ["foo.a","foo.b"])

I have a service in module foo.b say:

  angular.module("foo.b", [])

  angular.module("foo.b").factory("helper",helperFn);

which I want to use in one of my controllers in foo.a.

What I have done is simple dependency injection:

 angular.module("foo.a", []);

 angular.module("foo.a")
        .controller("MyController",["helper",MyControllerFn]);

which is working.

My questions are

  1. How am I getting the "helper" service from module foo.b even though it is not declared as a dependency for module a?
  2. Will it break at a later stage?
  3. If it is correct, is this a good practice?
like image 894
Soham Nakhare Avatar asked Aug 25 '15 04:08

Soham Nakhare


People also ask

What components can be injected as a dependency in AngularJS?

Which Component can be Injected as a Dependency In AngularJS? In Angular. JS, dependencies are injected by using an “injectable factory method” or “constructor function”. These components can be injected with “service” and “value” components as dependencies.

What are the advantages of dependency injection in AngularJS?

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.

How do I inject a module in AngularJS?

Injecting a value into an AngularJS controller function is done simply by adding a parameter with the same name as the value (the first parameter passed to the value() function when the value is defined). Here is an example: var myModule = angular. module("myModule", []); myModule.


1 Answers

Put the factory that you need access to in both modules in a third module. Have your two original modules inject a dependency to the third module.

angular.module("foo", ["foo.a", "foo.b"]);

angular.module("foo.a", ["foo.c"])
  .controller("MyController", ["helper", MyControllerFn]);

angular.module("foo.b", ["foo.c"]);

angular.module("foo.c")
  .factory("helper", helperFn);
like image 97
Stafford Williams Avatar answered Oct 17 '22 18:10

Stafford Williams