0

I want to have Angular module and a main controller. then some another controllers that lives another files.

Main module:

var app = angular.module("main", []);
app.controller("mainCtrl", function ($scope) {
  $scope.method1 = function (name) {
  }
}

And this is another controller inside a separate file:

var app = angular.module("main");//without []
app.controller("textCtrl", function ($scope) {
   $scope.method1(); //it works and i call method1 from mainCtrl(separate file)
});

i load this files like this:

<script src="/modules/app.js"></script>
<script src="/modules/secondapp.js"></script>

My problem is that, inside second controller i can call a method inside main controller, but i can't call a method inside second controller from main controller.

All structure is working but this problem bothers me.

At the end, i want to have separate files for each controller that all lives inside the same module and can share $scope and other variables in both files.

Another approach is using services, But problem is that in the main controller i have to inject service name from second controller and some times i did not load second controller and injecting that name throws to error.

I need a good structure for this.

Fcoder
  • 9,066
  • 17
  • 63
  • 100

2 Answers2

0

Seems like you have child parent controllers something like,

<div ng-controller="mainCtrl">
    <div ng-controller="textCtrl">

    </div>
</div>

then textCtrl can call the parent controller mainCtrl functions or can access parent variables also. and child controller properties not visible to the parent controller.

it doesn't matter two controllers in separate files because all of these are linked through var app.

to communicate between controllers there are many ways refer this post

using a service & emitting an event.

Community
  • 1
  • 1
Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92
0

data can be shared using services between two or more controllers. If you want same scope, you need to have data in $rootScope.

The other problem you are saying here can be solved by first loading js file with angular app defined in and then loading other files. In other files, you don't need to redefine angular app ( angular.module), as you have done above.

binariedMe
  • 4,309
  • 1
  • 18
  • 34