Access parent methods using controllerAs syntax in directives

I have a couple of nested directions. I am trying to be consistent and use controllerAs syntax. But I'm struggling to find a clean way for children to call parent methods that don't include a parent putting seemingly random functions in scope.

angular.module('app', [])

.directive('parent', function(){
    return {
        restrict: 'EA',
        controller: 'ParentController',
        controllerAs: 'parentCtrl',
    }
})
.directive('child', function(){
    return {
        restrict: 'EA',
        require: '^parent',
        controller: 'ChildController',
        controllerAs: 'childCtrl'
    }
})
.controller('ParentController', function($scope){
    var ctrl = this;

    ctrl.type = "hot";
    ctrl.nonInheritedFunction = nonInheritedFunction;
    $scope.inheritedFunction = inheritedFunction; // <-- trying to avoid this

    function nonInheritedFunction(type){
        ctrl.type = type;
        if(ctrl.type == 'cold'){
            //... do some Parent related things
        }
    }
    function inheritedFunction(type){
        // to illustrate that it does the same thing. Not a solution
        ctrl.nonInheritedFunction(type);
    }
})
.controller('ChildController', function($scope){
    var ctrl = this;

    ctrl.doAction = doAction;

    function doAction(action){
        if(action == 'flip_temperature'){
            // bah
            $scope.parentCtrl.nonInheritedFunction('hot');

            // much cleaner feeling
            $scope.inheritedFunction('hot');

            // wishing I could do something like
            // ctrl.nonInheritedFunction('hot');
        }
    }

    /**
    * template has access to type through `parentCtrl.type`
    * and the function through `parentCtrl.nonInheritedFunction`
    *
    * The only access the ChildController has is `$scope.parentCtrl.type`
    * Is there a way to keep $scope out of the equation?
    */

})
+4
source share
3 answers

transclude: true transclude .  , , . . $Parent transcluded scope .

0

angular > 1.3 bindToController .

, ,

scope: {
  onSomethingHappen: '&parentFunction'
},
controller: 'DirectiveController',
controllerAs: 'vm',
bindToController: true

: this.onSomethingHappen()

0

You must use the child and parent directives nested, so you can access the external controller.

 <parent >
<child >

</child></parent>
0
source

All Articles