0

I have a controller that depends on another controller (for settings info). I'm trying to use the Controller As pattern but I get an injection error.

Here's my controllers:

angular.module('app2', [])

.controller('ctrl1', [function () {
    var controller = this;
    controller.value = 6;
}])

.controller('ctrl2', ['ctrl1', function (ctrl1) {
    var controller = this;
    controller.testValue = 5;
    controller.runTest = function () { return ctrl1.Value * 2; };
}])

And here's how it's used

<body ng-controller="ctrl2 as ctrl">
    {{ ctrl.runTest() }}
</body>

I saw this article here but it didn't seem the same and I couldn't figure out how to get that solution working: AngularJS How to inject dependencies when using controller-as syntax

Community
  • 1
  • 1
Jason
  • 2,455
  • 4
  • 37
  • 48
  • 3
    Maybe it should depend on a shared `service`, not another `controller`? – Mikko Viitala Jun 30 '15 at 20:23
  • controllers can't be dependent on other controllers. Concept doesn't make sense. What are you trying to accomplish? – charlietfl Jun 30 '15 at 20:26
  • Actually one controller can depend on another, but it's more or less... not-something-one-should-do. – Mikko Viitala Jun 30 '15 at 20:31
  • 1
    @charlietfl - The application is a simple form that takes user input and updates a calculation at the bottom. I was trying to have one controller responsible for the user input and one for the calculation. I'm now thinking I'll get rid of the calculation one and have the calculation performed in a service instead. – Jason Jun 30 '15 at 21:02

1 Answers1

1

I really suggest you use a service to communicate between controllers and hold shared data.
One of many simple examples can be found e.g. here.

But, if you insist, then you need to inject $controller.

.controller('ctrl1', function() {
    var controller = this;
    controller.value = 6;
})

.controller('ctrl2', function($controller) {
    var controller = this;
    controller.testValue = 5;

    controller.runTest = function() {
      return $controller('ctrl1').value * 2; // <-note: '.Value' does not exist in ctrl1
    };
}); 
Community
  • 1
  • 1
Mikko Viitala
  • 8,344
  • 4
  • 37
  • 62