一个页面中有多个AngularJS应用程序

Multiple AngularJS apps in a single page

本文关键字:AngularJS 应用程序 一个      更新时间:2023-09-26

我在一页中有以下两个应用程序

导航栏模块

位于页面的导航栏中。通过主布局文件(im using laravel)包含在应用程序的每个页面中。包含搜索功能+导航栏功能,如(注销、登录)等。

立柱模块

仅在应用程序的"面板"页面中显示。基本上是从后端加载和显示帖子。

目前两者都是两个独立的应用程序,我使用angular.bootstrap加载它们。这两个应用程序都需要使用一个公共服务UserService。它基本上加载登录的用户详细信息。这是另一个模块的一部分,比如myapp.utils。该服务将解析html标签中的数据,并为消费者构建一个用户对象(Posts&Navbar应用程序)。但是,当我将服务注入两个应用程序时,User对象会生成两次。这就是我不想要的。对于下面的代码,我可以在控制台中看到两次打印的日志。

.factory('UserService', function(){
    console.log("Initing UserService");
    return {
        'User':...
    }
})

我无法将两个应用程序合并到一个更大的模块中,因为这两个模块都在两个不同的刀片模板(服务器视图文件)中声明。

请提出替代策略。

如果使用IIFE创建单例,然后使用.factory()方法创建单个实例或将其返回到共享模块中,则会将其实例化次数限制为仅一次。

这个单例实例可以使用Angular服务,但棘手的部分是,如果您需要每个Angular应用程序唯一的服务。例如CCD_ 5或CCD_。您可能必须将它们传递给使用它的共享服务上的函数,这将是痛苦的。

这是我的小演示,希望能很好地模拟您的场景。

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>