简体   繁体   English

AngularJS中多个ng-app的通用控制器

[英]Common controller for Multiple ng-app in AngularJS

I have a common controller that I need access in multiple ng-app scope 我有一个通用控制器,需要在多个ng-app范围内进行访问

Ex: 例如:

Controller 控制者

function commonCtrl($scope){
    $scope.data = { message: "Hello World" };
}

First ng-app 第一个ng-app

<div ng-app="firstApp">
    <div ng-controller="commonCtrl">
        <h1>{{data.message}}</h1>
    </div>
</div>

Second ng-app 第二个ng-app

<div ng-app="secondApp">
    <div ng-controller="commonCtrl">
        <h1>{{data.message}}</h1>
    </div>
</div>

This is not working. 这是行不通的。 I can set scope to one ng-app like 我可以将范围设置为一个ng-app

angular.module('firstApp', [])

But How can I make controller as common controller for all ng-app? 但是,如何使控制器成为所有ng-app的通用控制器?

Create a 3rd module and define the controller in that module. 创建第三个模块,并在该模块中定义控制器。 Refer the new module in the two ngApp module you have created. 请在您创建的两个ngApp模块中引用新模块。 Also the controller has to be defined using the module controller method. 同样,必须使用模块控制器方法定义控制器。

var sharedModule=angular.module('shared',[]);
sharedModule.controller('commonCtrl',['$scope',function($scope) {

}]);

Then use 然后使用

angular.module('firstApp', ['shared']);
angular.module('secondApp', ['shared']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM