javascript - AngularJS 依賴注入
我已經說了兩個模組:
foo.afoo.b
以及一個應用模組:
angular.module("foo", ["foo.a","foo.b"])
我在模塊 foo.b 中有一個服務,說:
angular.module("foo.b", [])
angular.module("foo.b").factory("helper",helperFn);
我想在我的其中一個控制器中的 foo.a 使用它。
我所做的是簡單的依賴注入:
angular.module("foo.a", []);
angular.module("foo.a")
.controller("MyController",["helper",MyControllerFn]);
正在運作。
我的問題是
- 即使模組 a 沒有宣告依賴,為什麼我仍然能從模組
foo.b獲取「helper」服務? - 它會在後期斷裂嗎?
- 如果是正確的,這是一個好做法嗎?
答案#1
將你需要在兩個模組中訪問的工廠放入第三個模組。讓你最初的兩個模組注入對第三個模組的依賴。
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);
