2

我正在嘗試爲不同的模塊使用相同的服務。有很多模塊,所以我試圖將它們注入到父模塊中。事情是這樣的:Angularjs:在不同模塊中使用通用服務

var app=angular.module('myapp',['module_1','module_2',....,'module_n']); 


var module_1=angular.module('myapp1',[]); 
var module_2=angular.module('myapp2',[]); 
var module_3=angular.module('myapp3',[]); 
. 
. 
. 
var module_n=angular.module('myappN',[]); 

並且是通用於所有ñ模塊的服務是這樣的:

.service('myService',function(){ 
...doing something here... 
}); 

現在我無法弄清楚如何使用該服務的所有子模塊。
我應該用哪個模塊關聯這個服務?我試過app.service('myService',function(){...}),但它沒有奏效。
我哪裏錯了?

編輯1:
而且我想與使用服務所有這些子模塊共享變量。我不知道是否,我正在通過使用服務進行共享變量,或者我應該使用供應商工廠執行此作業。

編輯2:
我發現這些鏈接,但我無法把握答案。參考它們並請提供我的回答
How to share a variable between multiple modules in AngularJS
Passing variable between controllers which are on different modules

+0

http://stackoverflow.com/questions/16725392/share-a-single-service-between-multiple-angular-js-apps –

回答

0

讓我們假設你想建立一個Service兩個Controllers之間共享某個變量。您應該能夠使用您Service執行以下操作:

MyService.js

// Lets suppose you want to share a certain variable between controllers 
angular 
.module('myApp') 
.service('myService', function() { 

    // If you wish you can inject and use $scope 
    var vm = this; 
    // Variable to share 
    vm.sharedItem; 

    // Method to set a certain value into a variable 
    function setItem(item){ 
    vm.sharedItem = item; 
    } 

    // Method to get that variable 
    function getItem(){ 
    return vm.sharedItem; 
    } 

    // Exposing your methods 
    return { 
    setItem  : setItem 
    getItem  : getItem 
    } 
}); 

SetController.js

angular 
.module('myApp') 
.controller('SetController', SetController); 

    // Inject your Service 
    function SetController(myService) { 

    var vm = this; 
    // variable used to set the value 
    vm.setMe = 'hello'; 

    // Call `setItem()` method from `myService` -> sharedItem will get setMe value 
    myService.setItem(vm.setMe); 

    console.log("Set shared item "+vm.setMe); 
    }; 

GetController.js

angular 
.module('myApp') 
.controller('GetController', GetController); 

    // Inject your Service 
    function SetController(myService) { 

    var vm = this; 
    // variable used to get shared the value 
    vm.getMe= null; 

    /* Call `getItem()` method from `myService` to get the shared 
    * value and assign it to `getMe`*/ 
    vm.getMe = myService.getItem(); 

    console.log("Got shared item "+vm.getMe); 
}; 

我提醒你可以在你的視圖中使用controllerName.var訪問this.var。確保您使用某個控制器是一個很好的解決方案。如果您願意,您可以隨時使用$scope

我希望我一直有幫助。

+0

很好說。但是我的疑問是,如何在控制器上共享'myService',當它們位於不同的模塊中?我研究過的東西將我引向做一個父模塊,它的依賴關係是需要共享「myService」的模塊。使服務成爲父模塊的一部分,然後將服務注入到這些子模塊中。但我不知道如何執行它 –

+0

爲什麼你不只是注入服務的孩子? – AndreaM16

+0

雖然我成功地使用了該服務,但仍然無法使用該服務共享這些子模塊中的變量,我試圖做同樣的事情。 –