1

I have a common controller that I need access in multiple ng-app scope

Ex:

Controller

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

First ng-app

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

Second 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

angular.module('firstApp', [])

But How can I make controller as common controller for all ng-app?

Chandu
  • 962
  • 2
  • 16
  • 33

1 Answers1

7

Create a 3rd module and define the controller in that module. Refer the new module in the two ngApp module you have created. 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']);
Chandermani
  • 42,589
  • 12
  • 85
  • 88