Angularjs 在页面上多次使用同一个 ng-app

Angularjs use same ng-app multiple times on page

我正在处理一个内容管理系统,它需要 "inject" 一个可重用的组件到页面中。

我想注入以下组件(html 和 javascript)。

<script type="text/javascript">
if(typeof angular == 'undefined') {
   document.write(unescape("%3Cscript type='text/javascript' src='/resources/scripts/lib/angular.min.js'%3E%3C/script%3E"));
   document.write(unescape("%3Cscript type='text/javascript' src='/resources/scripts/pricing/app.js'%3E%3C/script%3E"));     }    
}
  </script>           
<div ng-app="pricing" ng-controller="PriceController as pc" ng-init="pc.getPrices('myprod', 'PER')">
 Some text {{ pc.prices.msg["startdat tarief"] | jsDate }} . 
 More text {{ pc.prices.msg["einddat product"] | jsDate }}.

</div>   

该组件必须能够在页面上多次注入。

问题是控制器工作正常,但仅限于第一次注入。

这可能与我多次使用同一个应用程序有关。

我是 angular 的新手。

如何多次注入同一个组件?

请注意,我无法在更高级别上初始化应用程序。因为这需要内容管理器来编辑所有页面,所以我们只是想用 javascript 注入一个 HTML 组件(即代码片段)。

一个页面上不能有多个 ng-App 指令。来自 Angular.js documentation:

Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other.

如果将 ng-App 放在树的更高位置不是一个选项,您将不得不重新编写组件,以便每个组件都获得唯一的 angular.module() 并且在注入组件时,它需要开火 angular.bootstrap().

如果您能够向模块添加唯一 ID div,您可以手动 bootstrap 您的 angular 应用,如下所示:

function bootstrapAngular(id) {
    angular.bootstrap(document.getElementById('module-' + id), ['app']);
}

angular.module('app', []).controller('sample', function ($scope) {
   $scope.foo = 'bar'; 
});

bootstrapAngular(1);
bootstrapAngular(2);
bootstrapAngular(3);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="module-1">
    <div ng-controller="sample">
        {{ foo }}
    </div>
</div>
<div id="module-2">
    <div ng-controller="sample">
        {{ foo }}
    </div>
</div>
<div id="module-3">
    <div ng-controller="sample">
        {{ foo }}
    </div>
</div>