[英]Can Modules access variables stored in other modules that have not been imported, but both modules are exported to a main file?
[英]Access modules child modules service from main controller
我有這個模塊作為使用api
主要應用程序:
var app = angular.module('app.main', ['api']);
app.controller('Home', function($scope, api, search){
$scope.search = function(){
api.search.lookup($scope.domain);
search.lookup($scope.domain);
};
});
然后,我有了使用其他一些模塊的api
,如下所示:
var app = angular.module('api', [
'api.search'
// other modules here
]);
app.service('api', function($cookies, $http, $rootScope, search){
// Some more code
});
搜索搜索module
如下所示:
var app = angular.module('api.search', []);
app.service('search', function($scope, $http){
this.lookup = function(domain){
// query
};
});
當我運行控制器並注入api
,無法訪問search
因為我收到TypeError: Cannot read property 'lookup' of undefined
,並且如果我注入search
,則會收到此錯誤:
Error: [$injector:unpr] http://errors.angularjs.org/1.4.3/$injector/unpr?p0=<div ng-view="" class="ng-scope" data-ng-animate="1">copeProvider%20%3C-%20%24scope%20%3C-%search
因此,如何從控制器訪問搜索?
看來,問題是您試圖將$scope
注入到服務生成函數中。
$scope
是僅可用於控制器的局部注入,這很有意義,因為作用域與定義控制器的位置有關,並且對單例服務沒有意義。
相反,您可以根據需要將$rootScope
注入服務。
app.service('search', function($rootScope, $http){
// ...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.