angular.bootstrap error: Error: [ng:btstrpd] App Already Bootstrapped with this Element

匿名 (未验证) 提交于 2019-12-03 00:57:01

问题:

I'm building a widget that depends on Angular along with a widget builder tool. The builder used Angular with ngApp attached to the html tag of the document.

When I load up the widget within the widget builder, I get the following error:

Error: [ng:btstrpd] App Already Bootstrapped with this Element '<div class="company-widget" id="widget-app" data-company="demoCorp">'

Here is the bootstrap function:

angular.bootstrap('#widget-app', ["myWidget"]);

For all intents and purposes, the rest of the myWidget app is a pretty standard mix of controllers and services.

I was following along with this blog post on how to allow multiple ngApp directives in a single page, however I didn't realize until after I set this thing up that it says right at the end of the blog post that you can't nest apps, which is what's happening here, and what may occur on a small number of sites that use this widget.

I can't redesign the widget-builder and I can reasonably assume that for any Angular sites where the widget is embedded, the host site will attach ngApp to the html tag.

My question is, is there a way to get around this limitation, even if it's a hacky solution? Is it possible to check if the page already has an app and inject the myWidget app into the host app as a dependency?

回答1:

You could try something like this:

https://jsfiddle.net/pavy/vnnuxgwo/

// Parent/host application var myApp = angular.module('myApp', []);  myApp.controller('AppCtrl',     function($scope) {         $scope.name = 'YourName';     } );  // Third party module // This needs to happen after myApp is defined var myWidget = angular.module('myApp'); myWidget.controller('MyWidgetCtrl',     function($scope) {         $scope.widgetName = 'This is my widget.';     } );

The third party module code (your widget) needs to come after the host app (in your case, this would be the Widget Builder) code.

You're also dependent on the module name of the host app, so if it changes, your code will break. There are likely ways to programmatically get the loaded Angular app name, which would help in this regard.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!