簡體   English   中英

單個頁面中有多個AngularJS應用

[英]Multiple AngularJS apps in a single page

我在一個頁面中有以下2個應用

導航欄模塊

位於頁面的導航欄中。 通過主布局文件(使用laravel)包含在應用程序的每個頁面中。 包含搜索功能+導航欄功能(注銷,登錄)等。

帖子模塊

僅在應用程序的“儀表板”頁面中顯示。 基本上是從后端加載並顯示帖子。

目前,兩者都是兩個獨立的應用程序,我使用angular.bootstrap加載它們。 這兩個應用程序都需要使用通用服務UserService 基本上會加載已登錄的用戶詳細信息。 這是另一個模塊的一部分,例如myapp.utils 此服務將解析html標記中的數據,並為用戶准備一個User對象(Posts和Navbar應用程序)。 但是,當我將服務注入兩個應用程序時,User對象將生成兩次。 這是我不想要的。 對於以下代碼,我可以在控制台中看到兩次打印日志。

.factory('UserService', function(){
    console.log("Initing UserService");

    return {
        'User':...
    }
})

我不能將兩個應用程序合並到一個更大的模塊中,因為兩個模塊都在兩個不同的刀片服務器模板(服務器視圖文件)中聲明。

請提出一種替代策略。

如果使用IIFE創建單例,然后使用.factory()方法創建單個實例或將其返回到共享模塊中,則將實例化實例的次數限制為一個。

這個單例實例可以使用Angular服務,但棘手的部分是如果您需要每個Angular應用程序唯一的服務。 $rootScope$rootElement 您可能必須將它們傳遞給使用它的共享服務上的函數,這將很痛苦。

這是我的小演示,希望可以很好地模擬您的情況。

 var timesInstantiated = 0; (function() { var singletonInstance = null; function MyService($filter) { this.$filter = $filter; console.log('Creating sharedSvc instance'); timesInstantiated++; } MyService.prototype.strikeItRich = function() { return "I just found " + this.$filter('currency')(20, '$'); }; angular.module('shared', []) .factory('sharedSvc', function($filter) { if (!singletonInstance) { singletonInstance = new MyService($filter); } return singletonInstance; }); })(); var topApp = angular.module('topApp', ['shared']) .run(function($rootScope, sharedSvc) { $rootScope.topMessage = "I'm on top of the DOM (hey oh)"; $rootScope.sharedMessage = sharedSvc.strikeItRich(); }); var bottomApp = angular.module('bottomApp', ['shared']) .run(function($rootScope, sharedSvc) { $rootScope.bottomMessage = "Bottom's up! (Who switched gravity?!)"; $rootScope.sharedMessage = sharedSvc.strikeItRich(); }); document.addEventListener('DOMContentLoaded', function() { // bootstrap both modules console.log('Bootstrappin\\'...'); angular.bootstrap(document.getElementById('top-app'), ['topApp']); angular.bootstrap(document.getElementById('bottom-app'), ['bottomApp']); document.getElementById('times-instantiated').textContent = timesInstantiated; }, false); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> <div id="top-app"> <h3>Top App</h3> <p>Top Message: {{topMessage}}</p> <p>Shared Message: {{sharedMessage}}</p> </div> <div id="bottom-app"> <h3>Bottom App</h3> <p>Bottom Message: {{bottomMessage}}</p> <p>Shared Message: {{sharedMessage}}</p> </div> <hr/> <p>Times shared service instantiated: <span id="times-instantiated">?</span></p> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM