praveen_r
praveen_r

Reputation: 897

Calling a parent controller's function in the parent's context

I need my parent controller function getDataInParent to get called in the parent's controller's context itself.

Sample:

The child directive is correctly setup like this from within the parent directive template:

<child get-data="parentCtrl.getDataInParent"></child>

And here is a simple mockup of my controller implementations (see comments in getDataInParent):

// *** parent controller
controller('parentController', [...., function(){

var that = this;
that.someData = ...;

that.getDataInParent = function(someArgs){
    // Here I need to access "that.someData" and other 
    // properties/methods of this parent controller. But I can't!
    // Because this method doesn't seemed to be called in the context of this controller.
};
};]

// *** child controller
controller('childController', [...., function(){

var that = this;

// Hooked up correctly and am able to call the parent's function like this:
var dataFromParent = $scope.getData().(someArgs);
};]

This seems like a very common scenario that a lot of people would have encountered, so I am hoping there should be a straight forward solution for this in Angular.

Upvotes: 0

Views: 161

Answers (1)

Sasank Sunkavalli
Sasank Sunkavalli

Reputation: 3964

You can always create a local scope for a directive & bind the parent function to the local scope using this '&'. Suppose this is your html

<child get-data="parentCtrl.getDataInParent(params)"></child>

This should be your directive code.

angular
    .module('SampleApp')
    .directive('child', child);

/* @ngInject */
function child() {
    var directive = {
        restrict: 'E',
        templateUrl: 'templateUrl',
        scope: {
          getData : '&'
        },
        link: linkFunc,
        controller: 'Controller',
        controllerAs: 'vm'
    };

    return directive;

    function linkFunc(scope, el, attr, ctrl) {
      // Calling parent method here
      var dataFromParent = $scope.getData({params: "SomeParams"});
    }
}

Working Plunker : https://plnkr.co/edit/4n61WF4JN3eT2QcdnnTw?p=preview

Upvotes: 1

Related Questions