0
\$\begingroup\$

This is a simple AngularJs application with two nested controllers. We need to pass data from the parent to the child Controller.

The first thing you find when googling for a solution would be this, by calling $scope.$parent in the child controller:

angular.module("outerModule", [])
  .component('outerModule', {
      controller: function($scope) {
        $scope.innerModuleConfigData = {
          text : 'hello'
        }
      }
  }) 

angular.module("innerModule", [])
  .component('innerModule', {
      controller: function($scope) {
        console.log($scope.$parent.innerModuleConfigData.text);
      }
  })

The critique here is that the parent controller has to know exactly what to call its shared variable.

Another thing that comes to my mind is the thing with the nested scope when working with angular directives:

<inner-module configData="innerModuleConfigData"></inner-module>

I'm not sure if something like this works for nested controllers as well.

The consensus to a 'best practice' solution seems to be sending the data by a service, which is injected to both controllers. But this seems to be a little overheaded, if only small amounts of data are to be shared.

\$\endgroup\$
3
\$\begingroup\$

Having to refer to $scope.$parent is absolutely bad-practice, because dependencies will go up and down and all sorts of ways in your application. It will become a big mess. It is best to only pass dependencies down the scope chain, not up.

Exactly what you describe, you got two options. Go the nested scope way or use a service.

It is indeed best-practice to use a service when more logic is being handled. It's really up to you to choose between the two options. Both are good, but you need to think about the use-case. Will there be more data be passed along to both controllers; definitely go for the service. Is it just a simple pass this variable to the underlying controller go the nested scope route.

\$\endgroup\$
  • \$\begingroup\$ Thanks for the quick and thorough answer! I know nested Scope only from working with directives, do you have an example on how to do this with two controllers? \$\endgroup\$ – LocalHorst May 24 '17 at 7:49
  • \$\begingroup\$ Found a good documentation, for future reference. The Keyword is "Bindings": toddmotto.com/exploring-the-angular-1-5-component-method/… \$\endgroup\$ – LocalHorst May 24 '17 at 9:39
  • 1
    \$\begingroup\$ Bindings, most definitely. I forgot what it was called when writing the answer. Todd Motto is a big name in Angular world, you should check some of his posts out! :) \$\endgroup\$ – Vadiem Janssens May 24 '17 at 10:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.