【问题标题】:ng-controller with same name in different ng-app not working [duplicate]在不同的ng-app中具有相同名称的ng-controller不起作用[重复]
【发布时间】:2019-09-20 21:22:39
【问题描述】:

我在同一页面上声明了两个具有不同名称的 ng-app,但在这两个 ng-app 中,我必须为两个 ng-app 使用具有相同名称的通用 ng-controller。 但我没有得到想要的输出。它只是在初始化第一个 ng-controller。

我试过:只有一个 ng-app > ng-controller 很好,但是如果你跳过第一个 ng-app > ng-controller (即:var modules = ['secondScope'];)并尝试第二个初始化,它会显示错误在控制台中。

HTML:

<body>
<div ng-app="firstScope">
    <div ng-controller="classController">
      <div>{{name}}</div>
    </div> 
</div>

<div ng-app="secondScope">
    <div ng-controller="classController">
      <div>{{name}}</div>
    </div>
</div>
</body>

脚本:

var modules = ['firstScope', 'secondScope'];

angular.forEach(modules, function(mod){
    console.log(mod);
    var myApp = angular.module(mod, []);
    myApp.controller('classController', classController);
});

function classController($scope) {
    console.log('classController');
    $scope.name = "Child 1 Controller";
};

【问题讨论】:

    标签: angularjs module ng-controller


    【解决方案1】:

    问题不在于控制器的初始化,而在于模块作为 Angular 仅自动初始化一个应用程序。对于其他应用程序,您需要手动初始化它,如下所示。

    var modules = ['firstScope', 'secondScope'];
    
    angular.forEach(modules, function(mod){
        console.log(mod);
        var myApp = angular.module(mod, []);
        myApp.controller('classController', classController);
    });
    
     // manually initializing the app
    angular.bootstrap(document.getElementById('secondApp'), ['secondScope']);
    
    function classController($scope) {
        console.log('classController');
        $scope.name = "Child 1 Controller";
    };
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.min.js"></script>
    <div ng-app="firstScope">
        <div ng-controller="classController">
          <div>{{name}}</div>
        </div> 
    </div>
    
    <div ng-app="secondScope" id="secondApp">
        <div ng-controller="classController">
          <div>{{name}}</div>
        </div>
    </div>

    【讨论】:

    • 谢谢 Nikhil 的回答。但我有n 模块的编号。那我需要手动初始化吗?那里没有简化的方法吗?
    • 你可以遍历它们并调用初始化应用程序的函数
    猜你喜欢
    • 2014-05-06
    • 2017-01-15
    • 2018-12-17
    • 1970-01-01
    • 2018-03-27
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多