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

4
  • 3
    Maybe it should depend on a shared service, not another controller? Commented Jun 30, 2015 at 20:23
  • controllers can't be dependent on other controllers. Concept doesn't make sense. What are you trying to accomplish? Commented Jun 30, 2015 at 20:26
  • Actually one controller can depend on another, but it's more or less... not-something-one-should-do. Commented Jun 30, 2015 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. Commented Jun 30, 2015 at 21:02

1 Answer 1

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
    };
}); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.