在一个页面上引导多个角度应用程序会导致控制器未定义错误

Bootstrapping multiple angular apps on a page causes the error of controller undefined

本文关键字:应用程序 错误 未定义 控制器 一个      更新时间:2023-09-26

我的页面上有两个角度的应用程序。第一个是使用主体上的"ng-app"指令引导的。第二个应用程序使用 angular.bootstrap 方法手动初始化。

第一个自动引导的应用

<body ng-cloak ng-app="app">
<section id="mainbody">
  <div class="container radar-main-container">
    @RenderBody()
  </div>
</section>

下面是主应用程序的应用程序.js

var commonModule = angular.module('common', ['ui.router']);
var appMainModule = angular.module('app', ['common']);

手动引导的第二个应用

@section footerScript {
  angular.bootstrap(document.getElementById('signup'), ['signupApp']);
}

目录

<div id="signup" ng-app="signupApp" ng-controller="SignupController">
  <div ui-view></div>
</div>

在第二个模块中创建的控制器:

signupModule.controller("SignupController", ['$scope', '$location',
    function($scope, $location, $window) {
}
signupModule.controller("PackageInfoController", ['$scope', '$location',
    function($scope, $location) {
}

当我运行此代码时,我收到错误"SignupController"不是未定义的函数,它将我带到此链接错误

也许这对你有帮助,因为它工作得很好。

网页模板

<!DOCTYPE html>
<html>    
  <head>
    ...
    <script src="app.js"></script>
  </head>
  <body>
    <div ng-app="app" ng-controller="AppCtrl">
      main
    </div>
    <div id="signup" ng-controller="SignupCtrl">
      signup
    </div>
    <script>
      // @section footerScript
      angular.element(document).ready(function() {
        angular.bootstrap(document.getElementById('signup'), ['signup','common']);
      });
  </body>
</html>

应用.js

var common = angular.module('common', []);
var app = angular.module('app', ['common']);
app.controller('AppCtrl', function($scope) {});
var signup = angular.module('signup', ['common']);
signup.controller('SignupCtrl', function($scope) {});

首先,您的应用程序不得嵌套(一个嵌套在另一个内部)。您的应用程序必须出局,而不是在正文标签上。第二件事是,您只能在html文件中使用一次ng-app。