2

I've found a few similar questions on stackoverflow but no satisfying answer.

I prefer to hold most of directives logic in their controllers with bindToController and controllerAs.

So the standard communication beetwen 2 directives looks like:

<parent-directive>
    <child-directive></child-directive>
</parent-directive>

angular.module('app').
    directive('parent', function() {
        return {
            scope: {},
            restrict: 'E',
            controller: function() {
                this.doSomething = function() {
                    console.log('Consider it done!');
                };
            },
            controllerAs: 'vm'
        }
    }).
    directive('child', function() {
       return {
           restrict: 'E',
           require: '^parent',
           link: function($scope, $element, $attrs, parentController) {
               parentController.doSomething();
           }
       }
    });

This pattern of course works as expected. But when I want the children directive also use controller instead of linking function, I've to do something like this:

.directive('child', function() {
   return {
       restrict: 'E',
       require: ['child', '^parent'],
       controllerAs: 'vm',
       controller: function() {
           this._parentController = null;
           var vm = this;
           this.doSomethingInChild = function() {
               var iDepnedOnThis = this._parentController.doSomething();
               //do something more with above call result...
           }.bind(this);
       }
       link: function($scope, $element, $attrs, controllers) {
           var vm = controllers[0];
           vm._parentController = controllers[1];
       }
   }    
});

It also works, but I'm not sure if this is clean and the best solution. Is there any way to get rid of the parentController to childController assignment to in linking function?

  • http://stackoverflow.com/questions/21453697/angularjs-access-parent-scope-from-child-controller – machei Jul 03 '15 at 22:26
  • @machei: IMHO linked question do not solve my problem. We have na guarantee that $scope.$parent in child is the $scope used by parent directive. Eg. when using ng-repeat on the child directive. – Michael Prokopowicz Jul 03 '15 at 22:35

1 Answers1

0

Easy... look at example:

angular.module('app').
    directive('parent', function() {
        return {
            scope: {},
            restrict: 'E',
            controller: function() {
               this.doSomething = function(){}
               $scope.scope = this;
            }
        }
    })


<parent-directive>
    <child-directive ng-parent="scope"></child-directive>
</parent-directive>

And u need to make access to attribute ng-parentfrom child-driective.

machei
  • 337
  • 2
  • 16